agora inbox for [email protected]help / color / mirror / Atom feed
[PATCH v7 3/3] handle relation statistics correctly during rewrites 108+ messages / 2 participants [nested] [flat]
* [PATCH v7 3/3] handle relation statistics correctly during rewrites @ 2025-11-04 13:52 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Bertrand Drouvot @ 2025-11-04 13:52 UTC (permalink / raw) Now that PGSTAT_KIND_RELATION is keyed by refilenode, we need to handle rewrites. To do so, this patch: - Adds PgStat_PendingRewrite, a new struct to track rewrite operations within a transaction, storing the old locator, new locator, and original locator (for rewrite chains). This allows stats to be copied from the original location to the final location at commit time. - Adds a new function, pgstat_mark_rewrite(), called when a table rewrite begins. It records the rewrite operation in a local list and detects rewrite chains by checking if the old_locator matches any existing new_locator, preserving the chain's original_locator. - Modifies pgstat_copy_relation_stats(), to accept RelFileLocators instead of Relations, with a new increment parameter to accumulate stats (needed for rewrite chains with DML between rewrites). - Ensures that AtEOXact_PgStat_Relations(), AtPrepare_PgStat_Relations(), pgstat_twophase_postcommit()/postabort() pgstat_drop_relation() handle the PgStat_PendingRewrite list correctly. Note that due to the new flush call in pgstat_twophase_postcommit() we can not call GetCurrentTransactionStopTimestamp() in pgstat_relation_flush_cb(). So, adding a check to handle this special case and call GetCurrentTimestamp() instead. Note that we'd call GetCurrentTimestamp() only if there is a rewrite, so that the GetCurrentTimestamp() extra cost should be negligible. Another solution could be to trigger the flush from FinishPreparedTransaction() but that's not worth the extra complexity. The new pending_rewrites list is traversed in multiple places. The overhead should be negligible in comparison to a rewrite and the list should not contain a lot of rewrites in practice. The pending_rewrites list is traversed in multiple places. In typical usage, the list will contain only a few entries so the traversal cost is negligible ( furthermore in comparison to a rewrite). --- src/backend/catalog/index.c | 2 +- src/backend/commands/cluster.c | 5 + src/backend/commands/tablecmds.c | 6 + src/backend/utils/activity/pgstat_relation.c | 391 ++++++++++++++++++- src/backend/utils/activity/pgstat_xact.c | 25 +- src/backend/utils/cache/relcache.c | 6 + src/include/pgstat.h | 5 +- src/tools/pgindent/typedefs.list | 1 + 8 files changed, 424 insertions(+), 17 deletions(-) 92.8% src/backend/utils/activity/ 4.9% src/backend/ diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 5d9db167e59..8b6a7652fcf 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1795,7 +1795,7 @@ index_concurrently_swap(Oid newIndexId, Oid oldIndexId, const char *oldName) changeDependenciesOn(RelationRelationId, oldIndexId, newIndexId); /* copy over statistics from old to new index */ - pgstat_copy_relation_stats(newClassRel, oldClassRel); + pgstat_copy_relation_stats(newClassRel->rd_locator, oldClassRel->rd_locator, false); /* Copy data of pg_statistic from the old index to the new one */ CopyStatistics(oldIndexId, newIndexId); diff --git a/src/backend/commands/cluster.c b/src/backend/commands/cluster.c index b55221d44cd..da75dfa6ab8 100644 --- a/src/backend/commands/cluster.c +++ b/src/backend/commands/cluster.c @@ -1196,6 +1196,11 @@ swap_relation_files(Oid r1, Oid r2, bool target_is_pg_class, rel1 = relation_open(r1, NoLock); rel2 = relation_open(r2, NoLock); + + /* Mark that a rewrite happened */ + if (RELKIND_HAS_STORAGE(rel1->rd_rel->relkind)) + pgstat_mark_rewrite(rel1->rd_locator, rel2->rd_locator); + rel2->rd_createSubid = rel1->rd_createSubid; rel2->rd_newRelfilelocatorSubid = rel1->rd_newRelfilelocatorSubid; rel2->rd_firstRelfilelocatorSubid = rel1->rd_firstRelfilelocatorSubid; diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index 3aac459e483..540923452fb 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -16848,6 +16848,7 @@ ATExecSetTableSpace(Oid tableOid, Oid newTableSpace, LOCKMODE lockmode) Oid reltoastrelid; RelFileNumber newrelfilenumber; RelFileLocator newrlocator; + RelFileLocator oldrlocator; List *reltoastidxids = NIL; ListCell *lc; @@ -16886,6 +16887,7 @@ ATExecSetTableSpace(Oid tableOid, Oid newTableSpace, LOCKMODE lockmode) newrlocator = rel->rd_locator; newrlocator.relNumber = newrelfilenumber; newrlocator.spcOid = newTableSpace; + oldrlocator = rel->rd_locator; /* hand off to AM to actually create new rel storage and copy the data */ if (rel->rd_rel->relkind == RELKIND_INDEX) @@ -16898,6 +16900,10 @@ ATExecSetTableSpace(Oid tableOid, Oid newTableSpace, LOCKMODE lockmode) table_relation_copy_data(rel, &newrlocator); } + /* mark that a rewrite happened */ + if (RELKIND_HAS_STORAGE(rel->rd_rel->relkind)) + pgstat_mark_rewrite(oldrlocator, newrlocator); + /* * Update the pg_class row. * diff --git a/src/backend/utils/activity/pgstat_relation.c b/src/backend/utils/activity/pgstat_relation.c index 7debb14bb5d..15b4663eb77 100644 --- a/src/backend/utils/activity/pgstat_relation.c +++ b/src/backend/utils/activity/pgstat_relation.c @@ -30,6 +30,19 @@ #include "utils/syscache.h" #include "utils/timestamp.h" +/* Pending rewrite operations for stats copying */ +typedef struct PgStat_PendingRewrite +{ + RelFileLocator old_locator; + RelFileLocator new_locator; + RelFileLocator original_locator; + int nest_level; /* Transaction nesting level where rewrite + * occurred */ + struct PgStat_PendingRewrite *next; +} PgStat_PendingRewrite; + +/* The pending rewrites list for current transaction */ +static PgStat_PendingRewrite *pending_rewrites = NULL; /* Record that's written to 2PC state file when pgstat state is persisted */ typedef struct TwoPhasePgStatRecord @@ -43,6 +56,8 @@ typedef struct TwoPhasePgStatRecord PgStat_Counter deleted_pre_truncdrop; RelFileLocator locator; /* table's rd_locator */ bool truncdropped; /* was the relation truncated/dropped? */ + RelFileLocator rewrite_old_locator; + int rewrite_nest_level; } TwoPhasePgStatRecord; @@ -54,27 +69,70 @@ static void restore_truncdrop_counters(PgStat_TableXactStatus *trans); /* - * Copy stats between relations. This is used for things like REINDEX + * Copy stats between RelFileLocator. This is used for things like REINDEX * CONCURRENTLY. */ void -pgstat_copy_relation_stats(Relation dst, Relation src) +pgstat_copy_relation_stats(RelFileLocator dst, RelFileLocator src, bool increment) { PgStat_StatTabEntry *srcstats; PgStatShared_Relation *dstshstats; PgStat_EntryRef *dst_ref; - srcstats = pgstat_fetch_stat_tabentry_ext(RelationGetRelid(src)); + srcstats = (PgStat_StatTabEntry *) pgstat_fetch_entry(PGSTAT_KIND_RELATION, + src.dbOid, + RelFileLocatorToPgStatObjid(src)); if (!srcstats) return; dst_ref = pgstat_get_entry_ref_locked(PGSTAT_KIND_RELATION, - dst->rd_rel->relisshared ? InvalidOid : MyDatabaseId, - RelationGetRelid(dst), + dst.dbOid, + RelFileLocatorToPgStatObjid(dst), false); dstshstats = (PgStatShared_Relation *) dst_ref->shared_stats; - dstshstats->stats = *srcstats; + + if (!increment) + dstshstats->stats = *srcstats; + else + { + /* Increment those statistics */ +#define RELFSTAT_ACC(fld, stats_to_add) \ + (dstshstats->stats.fld += stats_to_add->fld) + RELFSTAT_ACC(numscans, srcstats); + RELFSTAT_ACC(tuples_returned, srcstats); + RELFSTAT_ACC(tuples_fetched, srcstats); + RELFSTAT_ACC(tuples_inserted, srcstats); + RELFSTAT_ACC(tuples_updated, srcstats); + RELFSTAT_ACC(tuples_deleted, srcstats); + RELFSTAT_ACC(tuples_hot_updated, srcstats); + RELFSTAT_ACC(tuples_newpage_updated, srcstats); + RELFSTAT_ACC(live_tuples, srcstats); + RELFSTAT_ACC(dead_tuples, srcstats); + RELFSTAT_ACC(mod_since_analyze, srcstats); + RELFSTAT_ACC(ins_since_vacuum, srcstats); + RELFSTAT_ACC(blocks_fetched, srcstats); + RELFSTAT_ACC(blocks_hit, srcstats); + RELFSTAT_ACC(vacuum_count, srcstats); + RELFSTAT_ACC(autovacuum_count, srcstats); + RELFSTAT_ACC(analyze_count, srcstats); + RELFSTAT_ACC(autoanalyze_count, srcstats); + RELFSTAT_ACC(total_vacuum_time, srcstats); + RELFSTAT_ACC(total_autovacuum_time, srcstats); + RELFSTAT_ACC(total_analyze_time, srcstats); + RELFSTAT_ACC(total_autoanalyze_time, srcstats); +#undef RELFSTAT_ACC + + /* Replace those statistics */ +#define RELFSTAT_REP(fld, stats_to_rep) \ + (dstshstats->stats.fld = stats_to_rep->fld) + RELFSTAT_REP(lastscan, srcstats); + RELFSTAT_REP(last_vacuum_time, srcstats); + RELFSTAT_REP(last_autovacuum_time, srcstats); + RELFSTAT_REP(last_analyze_time, srcstats); + RELFSTAT_REP(last_autoanalyze_time, srcstats); +#undef RELFSTAT_REP + } pgstat_unlock_entry(dst_ref); } @@ -136,6 +194,7 @@ void pgstat_assoc_relation(Relation rel) { RelFileLocator locator; + PgStat_TableStatus *pgstat_info; Assert(rel->pgstat_enabled); Assert(rel->pgstat_info == NULL); @@ -165,14 +224,54 @@ pgstat_assoc_relation(Relation rel) locator.relNumber = rel->rd_id; } + /* + * If this relation was rewritten during the current transaction we may be + * reopening it with its new RelFileLocator. In that case, continue using + * the stats entry associated with the old locator rather than creating a + * new one. This ensures all stats from before and after the rewrite are + * tracked in a single entry which will be properly copied to the new + * locator at transaction commit. + */ + if (pending_rewrites != NULL) + { + PgStat_PendingRewrite *rewrite; + + for (rewrite = pending_rewrites; rewrite != NULL; rewrite = rewrite->next) + { + if (locator.dbOid == rewrite->new_locator.dbOid && + locator.spcOid == rewrite->new_locator.spcOid && + locator.relNumber == rewrite->new_locator.relNumber) + { + pgstat_info = pgstat_prep_relation_pending(rewrite->old_locator); + goto found_entry; + } + } + } + /* Else find or make the PgStat_TableStatus entry, and update link */ - rel->pgstat_info = pgstat_prep_relation_pending(locator); + pgstat_info = pgstat_prep_relation_pending(locator); + +found_entry: + rel->pgstat_info = pgstat_info; + + /* + * For relations stats, we key by physical file location, not by relation + * OID. This means during operations like ALTER TYPE it's possible that + * the relation OID changes but the relfilenode stays the same (no actual + * rewrite needed). Unlink the old relation first. + */ + if (pgstat_info->relation != NULL && + pgstat_info->relation != rel) + { + pgstat_info->relation->pgstat_info = NULL; + pgstat_info->relation = NULL; + } /* don't allow link a stats to multiple relcache entries */ - Assert(rel->pgstat_info->relation == NULL); + Assert(pgstat_info->relation == NULL); /* mark this relation as the owner */ - rel->pgstat_info->relation = rel; + pgstat_info->relation = rel; } /* @@ -215,14 +314,37 @@ pgstat_drop_relation(Relation rel) { int nest_level = GetCurrentTransactionNestLevel(); PgStat_TableStatus *pgstat_info; + bool skip_transactional_drop = false; /* don't track stats for relations without storage */ if (!RELKIND_HAS_STORAGE(rel->rd_rel->relkind)) return; - pgstat_drop_transactional(PGSTAT_KIND_RELATION, - rel->rd_locator.dbOid, - RelFileLocatorToPgStatObjid(rel->rd_locator)); + /* Check if this drop is part of a pending rewrite */ + if (pending_rewrites != NULL) + { + PgStat_PendingRewrite *rewrite; + + for (rewrite = pending_rewrites; rewrite != NULL; rewrite = rewrite->next) + { + if (rel->rd_locator.dbOid == rewrite->old_locator.dbOid && + rel->rd_locator.spcOid == rewrite->old_locator.spcOid && + rel->rd_locator.relNumber == rewrite->old_locator.relNumber) + { + skip_transactional_drop = true; + break; + } + } + } + + /* + * If it is part of a rewrite, drop its stats later, for example in + * AtEOXact_PgStat_Relations(), so skip it here. + */ + if (!skip_transactional_drop) + pgstat_drop_transactional(PGSTAT_KIND_RELATION, + rel->rd_locator.dbOid, + RelFileLocatorToPgStatObjid(rel->rd_locator)); if (!pgstat_should_count_relation(rel)) return; @@ -660,6 +782,48 @@ AtEOXact_PgStat_Relations(PgStat_SubXactStatus *xact_state, bool isCommit) } tabstat->trans = NULL; } + + /* preserve the stats in case of rewrite */ + if (isCommit && pending_rewrites != NULL) + { + PgStat_PendingRewrite *rewrite; + PgStat_PendingRewrite *prev = NULL; + PgStat_PendingRewrite *current = pending_rewrites; + PgStat_PendingRewrite *next; + + /* reverse the rewrites list to process in chronological order */ + while (current != NULL) + { + next = current->next; + current->next = prev; + prev = current; + current = next; + } + + /* now process rewrites in chronological order */ + for (rewrite = prev; rewrite != NULL; rewrite = rewrite->next) + { + PgStat_EntryRef *old_entry_ref; + + old_entry_ref = pgstat_fetch_pending_entry(PGSTAT_KIND_RELATION, + rewrite->old_locator.dbOid, + RelFileLocatorToPgStatObjid(rewrite->old_locator)); + + if (old_entry_ref && old_entry_ref->pending) + pgstat_relation_flush_cb(old_entry_ref, false); + + pgstat_copy_relation_stats(rewrite->new_locator, + rewrite->old_locator, true); + + /* drop old locator's stats */ + if (!pgstat_drop_entry(PGSTAT_KIND_RELATION, + rewrite->old_locator.dbOid, + RelFileLocatorToPgStatObjid(rewrite->old_locator))) + pgstat_request_entry_refs_gc(); + } + } + + pending_rewrites = NULL; } /* @@ -675,6 +839,30 @@ AtEOSubXact_PgStat_Relations(PgStat_SubXactStatus *xact_state, bool isCommit, in PgStat_TableXactStatus *trans; PgStat_TableXactStatus *next_trans; + /* + * If we don't commit then remove the associated rewrites if any, to keep + * the rewrite chain in sync with what will be eventually committed. + */ + if (!isCommit) + { + PgStat_PendingRewrite **rewrite_ptr = &pending_rewrites; + + while (*rewrite_ptr != NULL) + { + if ((*rewrite_ptr)->nest_level >= nestDepth) + { + PgStat_PendingRewrite *to_remove = *rewrite_ptr; + + *rewrite_ptr = (*rewrite_ptr)->next; + pfree(to_remove); + } + else + { + rewrite_ptr = &((*rewrite_ptr)->next); + } + } + } + for (trans = xact_state->first; trans != NULL; trans = next_trans) { PgStat_TableStatus *tabstat; @@ -754,11 +942,19 @@ void AtPrepare_PgStat_Relations(PgStat_SubXactStatus *xact_state) { PgStat_TableXactStatus *trans; + PgStat_PendingRewrite *rewrite; + /* + * For each tabstat, find its matching rewrite and remove it from the + * pending rewrites list. This way, after processing all tabstats, pending + * rewrites will only contain rewrite only transactions. + */ for (trans = xact_state->first; trans != NULL; trans = trans->next) { PgStat_TableStatus *tabstat PG_USED_FOR_ASSERTS_ONLY; TwoPhasePgStatRecord record; + PgStat_PendingRewrite **rewrite_ptr; + bool found_rewrite = false; Assert(trans->nest_level == 1); Assert(trans->upper == NULL); @@ -778,10 +974,83 @@ AtPrepare_PgStat_Relations(PgStat_SubXactStatus *xact_state) record.locator = tabstat->locator; record.truncdropped = trans->truncdropped; + record.rewrite_nest_level = 0; + + /* + * Look for a matching rewrite and remove it from pending rewrites. We + * check three possible matches: + * + * The new_locator when stats have been added after the rewrite. The + * old_locator when stats have been added before the rewrite but not + * after. The original_locator when this tabstat is part of a rewrite + * chain. + */ + rewrite_ptr = &pending_rewrites; + while (*rewrite_ptr != NULL) + { + rewrite = *rewrite_ptr; + + if ((record.locator.dbOid == rewrite->new_locator.dbOid && + record.locator.spcOid == rewrite->new_locator.spcOid && + record.locator.relNumber == rewrite->new_locator.relNumber) || + (tabstat->locator.dbOid == rewrite->old_locator.dbOid && + tabstat->locator.spcOid == rewrite->old_locator.spcOid && + tabstat->locator.relNumber == rewrite->old_locator.relNumber) || + (tabstat->locator.dbOid == rewrite->original_locator.dbOid && + tabstat->locator.spcOid == rewrite->original_locator.spcOid && + tabstat->locator.relNumber == rewrite->original_locator.relNumber)) + { + /* + * Found matching rewrite. Record the rewrite information and + * remove this rewrite from the list since it's now handled. + */ + record.rewrite_old_locator = rewrite->original_locator; + record.rewrite_nest_level = rewrite->nest_level; + record.locator = rewrite->new_locator; + found_rewrite = true; + + /* Remove from pending_rewrites list */ + *rewrite_ptr = rewrite->next; + pfree(rewrite); + break; + } + else + { + /* Move to next rewrite in the list */ + rewrite_ptr = &(rewrite->next); + } + } + + /* If no rewrite found, clear the rewrite fields */ + if (!found_rewrite) + { + memset(&record.rewrite_old_locator, 0, sizeof(RelFileLocator)); + } + + RegisterTwoPhaseRecord(TWOPHASE_RM_PGSTAT_ID, 0, + &record, sizeof(TwoPhasePgStatRecord)); + } + + /* + * Now process any rewrites still pending. These are rewrite only + * transactions. We need to preserve their stats even though there's no + * tabstat entry for them. + */ + for (rewrite = pending_rewrites; rewrite != NULL; rewrite = rewrite->next) + { + TwoPhasePgStatRecord record; + + memset(&record, 0, sizeof(TwoPhasePgStatRecord)); + record.locator = rewrite->new_locator; + record.rewrite_old_locator = rewrite->original_locator; + record.rewrite_nest_level = rewrite->nest_level; + record.truncdropped = false; RegisterTwoPhaseRecord(TWOPHASE_RM_PGSTAT_ID, 0, &record, sizeof(TwoPhasePgStatRecord)); } + + pending_rewrites = NULL; } /* @@ -804,6 +1073,8 @@ PostPrepare_PgStat_Relations(PgStat_SubXactStatus *xact_state) tabstat = trans->parent; tabstat->trans = NULL; } + + pending_rewrites = NULL; } /* @@ -839,6 +1110,29 @@ pgstat_twophase_postcommit(FullTransactionId fxid, uint16 info, pgstat_info->counts.changed_tuples += rec->tuples_inserted + rec->tuples_updated + rec->tuples_deleted; + + if (rec->rewrite_nest_level > 0) + { + PgStat_EntryRef *old_entry_ref; + + /* Flush any pending stats for old locator first */ + old_entry_ref = pgstat_fetch_pending_entry(PGSTAT_KIND_RELATION, + rec->rewrite_old_locator.dbOid, + RelFileLocatorToPgStatObjid(rec->rewrite_old_locator)); + + if (old_entry_ref && old_entry_ref->pending) + pgstat_relation_flush_cb(old_entry_ref, false); + + /* Copy stats from old to new locator */ + pgstat_copy_relation_stats(rec->locator, rec->rewrite_old_locator, + true); + + /* Drop old locator's stats */ + if (!pgstat_drop_entry(PGSTAT_KIND_RELATION, + rec->rewrite_old_locator.dbOid, + RelFileLocatorToPgStatObjid(rec->rewrite_old_locator))) + pgstat_request_entry_refs_gc(); + } } /* @@ -853,9 +1147,26 @@ pgstat_twophase_postabort(FullTransactionId fxid, uint16 info, { TwoPhasePgStatRecord *rec = (TwoPhasePgStatRecord *) recdata; PgStat_TableStatus *pgstat_info; + RelFileLocator target_locator; + + /* + * For aborted transactions with rewrites (like TRUNCATE), we need to + * restore stats to the old locator, not the new one. The new locator + * should be dropped since the rewrite is being rolled back. + */ + if (rec->rewrite_nest_level > 0) + { + /* Use the old locator */ + target_locator = rec->rewrite_old_locator; + } + else + { + /* No rewrite, use the original locator */ + target_locator = rec->locator; + } /* Find or create a tabstat entry for the target locator */ - pgstat_info = pgstat_prep_relation_pending(rec->locator); + pgstat_info = pgstat_prep_relation_pending(target_locator); /* Same math as in AtEOXact_PgStat, abort case */ if (rec->truncdropped) @@ -910,7 +1221,17 @@ pgstat_relation_flush_cb(PgStat_EntryRef *entry_ref, bool nowait) tabentry->numscans += lstats->counts.numscans; if (lstats->counts.numscans) { - TimestampTz t = GetCurrentTransactionStopTimestamp(); + TimestampTz t; + + /* + * Checking the transaction state due to the flush call in + * pgstat_twophase_postcommit() that would break the assertion on the + * state in GetCurrentTransactionStopTimestamp(). + */ + if (!IsTransactionState()) + t = GetCurrentTransactionStopTimestamp(); + else + t = GetCurrentTimestamp(); if (t > tabentry->lastscan) tabentry->lastscan = t; @@ -1162,3 +1483,45 @@ pgstat_reloid_to_relfilelocator(Oid reloid, RelFileLocator *locator) ReleaseSysCache(tuple); return result; } + +/* + * Mark that a relation rewrite has occurred, preserving the original locator + * so stats can be copied at transaction commit. + */ +void +pgstat_mark_rewrite(RelFileLocator old_locator, RelFileLocator new_locator) +{ + PgStat_PendingRewrite *rewrite; + PgStat_PendingRewrite *existing; + RelFileLocator original_locator = old_locator; + + for (existing = pending_rewrites; existing != NULL; existing = existing->next) + { + if (old_locator.dbOid == existing->new_locator.dbOid && + old_locator.spcOid == existing->new_locator.spcOid && + old_locator.relNumber == existing->new_locator.relNumber) + { + original_locator = existing->original_locator; + break; + } + } + + /* Allocate in TopTransactionContext memory context */ + rewrite = MemoryContextAlloc(TopTransactionContext, + sizeof(PgStat_PendingRewrite)); + + rewrite->old_locator = old_locator; + rewrite->new_locator = new_locator; + rewrite->original_locator = original_locator; + rewrite->nest_level = GetCurrentTransactionNestLevel(); + + /* Add to the list */ + rewrite->next = pending_rewrites; + pending_rewrites = rewrite; +} + +void +pgstat_clear_rewrite(void) +{ + pending_rewrites = NULL; +} diff --git a/src/backend/utils/activity/pgstat_xact.c b/src/backend/utils/activity/pgstat_xact.c index bc9864bd8d9..f8cf3755ce2 100644 --- a/src/backend/utils/activity/pgstat_xact.c +++ b/src/backend/utils/activity/pgstat_xact.c @@ -55,6 +55,8 @@ AtEOXact_PgStat(bool isCommit, bool parallel) } pgStatXactStack = NULL; + pgstat_clear_rewrite(); + /* Make sure any stats snapshot is thrown away */ pgstat_clear_snapshot(); } @@ -360,8 +362,29 @@ create_drop_transactional_internal(PgStat_Kind kind, Oid dboid, uint64 objid, bo void pgstat_create_transactional(PgStat_Kind kind, Oid dboid, uint64 objid) { - if (pgstat_get_entry_ref(kind, dboid, objid, false, NULL)) + PgStat_EntryRef *entry_ref; + + entry_ref = pgstat_get_entry_ref(kind, dboid, objid, false, NULL); + + if (entry_ref) { + /* + * For relations stats, we key by physical file location, not by + * relation OID. This means during operations like ALTER TYPE where + * the relation OID changes but the relfilenode stays the same (no + * actual rewrite needed), we'll find an existing entry. + * + * This is expected behavior, we want to preserve stats across the + * catalog change. Simply reset and recreate the entry for the new + * relation OID without warning. + */ + if (kind == PGSTAT_KIND_RELATION) + { + pgstat_reset(kind, dboid, objid); + create_drop_transactional_internal(kind, dboid, objid, true); + return; + } + ereport(WARNING, errmsg("resetting existing statistics for kind %s, db=%u, oid=%" PRIu64, (pgstat_get_kind_info(kind))->name, dboid, diff --git a/src/backend/utils/cache/relcache.c b/src/backend/utils/cache/relcache.c index 915d0bc9084..7a7f8023eb3 100644 --- a/src/backend/utils/cache/relcache.c +++ b/src/backend/utils/cache/relcache.c @@ -85,6 +85,7 @@ #include "utils/inval.h" #include "utils/lsyscache.h" #include "utils/memutils.h" +#include "utils/pgstat_internal.h" #include "utils/relmapper.h" #include "utils/resowner.h" #include "utils/snapmgr.h" @@ -3780,6 +3781,7 @@ RelationSetNewRelfilenumber(Relation relation, char persistence) MultiXactId minmulti = InvalidMultiXactId; TransactionId freezeXid = InvalidTransactionId; RelFileLocator newrlocator; + RelFileLocator oldrlocator = relation->rd_locator; if (!IsBinaryUpgrade) { @@ -3951,6 +3953,10 @@ RelationSetNewRelfilenumber(Relation relation, char persistence) table_close(pg_class, RowExclusiveLock); + /* Mark that a rewrite happened */ + if (RELKIND_HAS_STORAGE(relation->rd_rel->relkind)) + pgstat_mark_rewrite(oldrlocator, newrlocator); + /* * Make the pg_class row change or relation map change visible. This will * cause the relcache entry to get updated, too. diff --git a/src/include/pgstat.h b/src/include/pgstat.h index 5d0fe79f7e3..332dffde400 100644 --- a/src/include/pgstat.h +++ b/src/include/pgstat.h @@ -665,7 +665,7 @@ extern PgStat_FunctionCounts *find_funcstat_entry(Oid func_id); extern void pgstat_create_relation(Relation rel); extern void pgstat_drop_relation(Relation rel); -extern void pgstat_copy_relation_stats(Relation dst, Relation src); +extern void pgstat_copy_relation_stats(RelFileLocator dst, RelFileLocator src, bool increment); extern void pgstat_init_relation(Relation rel); extern void pgstat_assoc_relation(Relation rel); @@ -677,6 +677,9 @@ extern void pgstat_report_vacuum(RelFileLocator locator, PgStat_Counter livetupl extern void pgstat_report_analyze(Relation rel, PgStat_Counter livetuples, PgStat_Counter deadtuples, bool resetcounter, TimestampTz starttime); +extern void pgstat_mark_rewrite(RelFileLocator old_locator, + RelFileLocator new_locator); +extern void pgstat_clear_rewrite(void); /* * If stats are enabled, but pending data hasn't been prepared yet, call diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index 432509277c9..bd8fcb16dcf 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -2248,6 +2248,7 @@ PgStat_KindInfo PgStat_LocalState PgStat_PendingDroppedStatsItem PgStat_PendingIO +PgStat_PendingRewrite PgStat_SLRUStats PgStat_ShmemControl PgStat_Snapshot -- 2.34.1 --KMYjwlsACqdYx2P8-- ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-06-16 11:54 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-06-16 11:54 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 9407c357f27..fa5a53d04ff 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 9ab74c8df0a..2af586669ae 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -689,6 +689,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1376,22 +1378,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1408,9 +1404,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1495,9 +1489,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1524,7 +1516,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1537,8 +1529,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -3926,27 +3918,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4034,11 +4018,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 2debadd86ed..28b34fd4387 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -503,13 +503,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -528,15 +526,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -546,7 +538,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -670,11 +662,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1207,7 +1196,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index 38f9ffcd04f..c0f6217caa6 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23245,9 +23245,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23379,18 +23377,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23427,11 +23416,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index a4abb29cf64..8922d713916 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index b4d5abbaca7..90234c3f736 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1325,6 +1325,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v01-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-06-16 11:54 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-06-16 11:54 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 9407c357f27..fa5a53d04ff 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 9ab74c8df0a..2af586669ae 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -689,6 +689,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1376,22 +1378,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1408,9 +1404,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1495,9 +1489,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1524,7 +1516,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1537,8 +1529,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -3926,27 +3918,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4034,11 +4018,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 2debadd86ed..28b34fd4387 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -503,13 +503,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -528,15 +526,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -546,7 +538,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -670,11 +662,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1207,7 +1196,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index 38f9ffcd04f..c0f6217caa6 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23245,9 +23245,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23379,18 +23377,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23427,11 +23416,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index a4abb29cf64..8922d713916 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index b4d5abbaca7..90234c3f736 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1325,6 +1325,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v01-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-06-16 11:54 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-06-16 11:54 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 9407c357f27..fa5a53d04ff 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 9ab74c8df0a..2af586669ae 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -689,6 +689,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1376,22 +1378,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1408,9 +1404,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1495,9 +1489,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1524,7 +1516,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1537,8 +1529,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -3926,27 +3918,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4034,11 +4018,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 2debadd86ed..28b34fd4387 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -503,13 +503,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -528,15 +526,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -546,7 +538,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -670,11 +662,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1207,7 +1196,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index 38f9ffcd04f..c0f6217caa6 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23245,9 +23245,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23379,18 +23377,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23427,11 +23416,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index a4abb29cf64..8922d713916 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index b4d5abbaca7..90234c3f736 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1325,6 +1325,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v01-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-06-16 11:54 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-06-16 11:54 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 9407c357f27..fa5a53d04ff 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 9ab74c8df0a..2af586669ae 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -689,6 +689,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1376,22 +1378,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1408,9 +1404,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1495,9 +1489,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1524,7 +1516,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1537,8 +1529,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -3926,27 +3918,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4034,11 +4018,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 2debadd86ed..28b34fd4387 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -503,13 +503,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -528,15 +526,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -546,7 +538,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -670,11 +662,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1207,7 +1196,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index 38f9ffcd04f..c0f6217caa6 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23245,9 +23245,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23379,18 +23377,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23427,11 +23416,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index a4abb29cf64..8922d713916 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index b4d5abbaca7..90234c3f736 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1325,6 +1325,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v01-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-06-16 11:54 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-06-16 11:54 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 9407c357f27..fa5a53d04ff 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 9ab74c8df0a..2af586669ae 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -689,6 +689,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1376,22 +1378,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1408,9 +1404,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1495,9 +1489,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1524,7 +1516,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1537,8 +1529,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -3926,27 +3918,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4034,11 +4018,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 2debadd86ed..28b34fd4387 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -503,13 +503,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -528,15 +526,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -546,7 +538,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -670,11 +662,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1207,7 +1196,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index 38f9ffcd04f..c0f6217caa6 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23245,9 +23245,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23379,18 +23377,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23427,11 +23416,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index a4abb29cf64..8922d713916 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index b4d5abbaca7..90234c3f736 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1325,6 +1325,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v01-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-06-16 11:54 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-06-16 11:54 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 9407c357f27..fa5a53d04ff 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 9ab74c8df0a..2af586669ae 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -689,6 +689,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1376,22 +1378,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1408,9 +1404,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1495,9 +1489,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1524,7 +1516,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1537,8 +1529,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -3926,27 +3918,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4034,11 +4018,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 2debadd86ed..28b34fd4387 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -503,13 +503,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -528,15 +526,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -546,7 +538,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -670,11 +662,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1207,7 +1196,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index 38f9ffcd04f..c0f6217caa6 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23245,9 +23245,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23379,18 +23377,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23427,11 +23416,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index a4abb29cf64..8922d713916 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index b4d5abbaca7..90234c3f736 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1325,6 +1325,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v01-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-06-16 11:54 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-06-16 11:54 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 9407c357f27..fa5a53d04ff 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 9ab74c8df0a..2af586669ae 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -689,6 +689,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1376,22 +1378,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1408,9 +1404,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1495,9 +1489,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1524,7 +1516,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1537,8 +1529,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -3926,27 +3918,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4034,11 +4018,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 2debadd86ed..28b34fd4387 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -503,13 +503,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -528,15 +526,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -546,7 +538,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -670,11 +662,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1207,7 +1196,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index 38f9ffcd04f..c0f6217caa6 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23245,9 +23245,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23379,18 +23377,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23427,11 +23416,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index a4abb29cf64..8922d713916 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index b4d5abbaca7..90234c3f736 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1325,6 +1325,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v01-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-06-16 11:54 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-06-16 11:54 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 9407c357f27..fa5a53d04ff 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 9ab74c8df0a..2af586669ae 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -689,6 +689,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1376,22 +1378,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1408,9 +1404,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1495,9 +1489,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1524,7 +1516,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1537,8 +1529,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -3926,27 +3918,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4034,11 +4018,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 2debadd86ed..28b34fd4387 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -503,13 +503,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -528,15 +526,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -546,7 +538,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -670,11 +662,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1207,7 +1196,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index 38f9ffcd04f..c0f6217caa6 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23245,9 +23245,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23379,18 +23377,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23427,11 +23416,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index a4abb29cf64..8922d713916 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index b4d5abbaca7..90234c3f736 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1325,6 +1325,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v01-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-06-16 11:54 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-06-16 11:54 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 9407c357f27..fa5a53d04ff 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 9ab74c8df0a..2af586669ae 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -689,6 +689,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1376,22 +1378,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1408,9 +1404,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1495,9 +1489,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1524,7 +1516,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1537,8 +1529,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -3926,27 +3918,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4034,11 +4018,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 2debadd86ed..28b34fd4387 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -503,13 +503,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -528,15 +526,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -546,7 +538,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -670,11 +662,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1207,7 +1196,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index 38f9ffcd04f..c0f6217caa6 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23245,9 +23245,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23379,18 +23377,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23427,11 +23416,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index a4abb29cf64..8922d713916 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index b4d5abbaca7..90234c3f736 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1325,6 +1325,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v01-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-06-16 11:54 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-06-16 11:54 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 9407c357f27..fa5a53d04ff 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 9ab74c8df0a..2af586669ae 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -689,6 +689,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1376,22 +1378,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1408,9 +1404,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1495,9 +1489,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1524,7 +1516,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1537,8 +1529,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -3926,27 +3918,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4034,11 +4018,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 2debadd86ed..28b34fd4387 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -503,13 +503,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -528,15 +526,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -546,7 +538,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -670,11 +662,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1207,7 +1196,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index 38f9ffcd04f..c0f6217caa6 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23245,9 +23245,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23379,18 +23377,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23427,11 +23416,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index a4abb29cf64..8922d713916 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index b4d5abbaca7..90234c3f736 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1325,6 +1325,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v01-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-06-16 11:54 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-06-16 11:54 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 9407c357f27..fa5a53d04ff 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 9ab74c8df0a..2af586669ae 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -689,6 +689,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1376,22 +1378,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1408,9 +1404,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1495,9 +1489,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1524,7 +1516,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1537,8 +1529,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -3926,27 +3918,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4034,11 +4018,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 2debadd86ed..28b34fd4387 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -503,13 +503,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -528,15 +526,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -546,7 +538,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -670,11 +662,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1207,7 +1196,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index 38f9ffcd04f..c0f6217caa6 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23245,9 +23245,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23379,18 +23377,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23427,11 +23416,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index a4abb29cf64..8922d713916 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index b4d5abbaca7..90234c3f736 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1325,6 +1325,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v01-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-06-16 11:54 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-06-16 11:54 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 9407c357f27..fa5a53d04ff 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 9ab74c8df0a..2af586669ae 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -689,6 +689,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1376,22 +1378,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1408,9 +1404,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1495,9 +1489,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1524,7 +1516,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1537,8 +1529,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -3926,27 +3918,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4034,11 +4018,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 2debadd86ed..28b34fd4387 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -503,13 +503,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -528,15 +526,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -546,7 +538,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -670,11 +662,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1207,7 +1196,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index 38f9ffcd04f..c0f6217caa6 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23245,9 +23245,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23379,18 +23377,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23427,11 +23416,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index a4abb29cf64..8922d713916 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index b4d5abbaca7..90234c3f736 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1325,6 +1325,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v01-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-06-16 11:54 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-06-16 11:54 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 9407c357f27..fa5a53d04ff 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 9ab74c8df0a..2af586669ae 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -689,6 +689,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1376,22 +1378,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1408,9 +1404,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1495,9 +1489,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1524,7 +1516,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1537,8 +1529,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -3926,27 +3918,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4034,11 +4018,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 2debadd86ed..28b34fd4387 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -503,13 +503,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -528,15 +526,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -546,7 +538,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -670,11 +662,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1207,7 +1196,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index 38f9ffcd04f..c0f6217caa6 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23245,9 +23245,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23379,18 +23377,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23427,11 +23416,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index a4abb29cf64..8922d713916 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index b4d5abbaca7..90234c3f736 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1325,6 +1325,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v01-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-06-16 11:54 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-06-16 11:54 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 9407c357f27..fa5a53d04ff 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 9ab74c8df0a..2af586669ae 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -689,6 +689,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1376,22 +1378,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1408,9 +1404,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1495,9 +1489,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1524,7 +1516,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1537,8 +1529,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -3926,27 +3918,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4034,11 +4018,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 2debadd86ed..28b34fd4387 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -503,13 +503,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -528,15 +526,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -546,7 +538,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -670,11 +662,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1207,7 +1196,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index 38f9ffcd04f..c0f6217caa6 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23245,9 +23245,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23379,18 +23377,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23427,11 +23416,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index a4abb29cf64..8922d713916 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index b4d5abbaca7..90234c3f736 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1325,6 +1325,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v01-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-06-16 11:54 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-06-16 11:54 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 9407c357f27..fa5a53d04ff 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 9ab74c8df0a..2af586669ae 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -689,6 +689,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1376,22 +1378,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1408,9 +1404,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1495,9 +1489,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1524,7 +1516,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1537,8 +1529,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -3926,27 +3918,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4034,11 +4018,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 2debadd86ed..28b34fd4387 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -503,13 +503,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -528,15 +526,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -546,7 +538,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -670,11 +662,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1207,7 +1196,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index 38f9ffcd04f..c0f6217caa6 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23245,9 +23245,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23379,18 +23377,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23427,11 +23416,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index a4abb29cf64..8922d713916 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index b4d5abbaca7..90234c3f736 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1325,6 +1325,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v01-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-06-16 11:54 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-06-16 11:54 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 9407c357f27..fa5a53d04ff 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 9ab74c8df0a..2af586669ae 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -689,6 +689,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1376,22 +1378,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1408,9 +1404,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1495,9 +1489,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1524,7 +1516,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1537,8 +1529,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -3926,27 +3918,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4034,11 +4018,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 2debadd86ed..28b34fd4387 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -503,13 +503,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -528,15 +526,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -546,7 +538,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -670,11 +662,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1207,7 +1196,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index 38f9ffcd04f..c0f6217caa6 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23245,9 +23245,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23379,18 +23377,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23427,11 +23416,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index a4abb29cf64..8922d713916 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index b4d5abbaca7..90234c3f736 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1325,6 +1325,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v01-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-06-16 11:54 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-06-16 11:54 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 9407c357f27..fa5a53d04ff 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 9ab74c8df0a..2af586669ae 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -689,6 +689,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1376,22 +1378,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1408,9 +1404,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1495,9 +1489,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1524,7 +1516,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1537,8 +1529,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -3926,27 +3918,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4034,11 +4018,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 2debadd86ed..28b34fd4387 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -503,13 +503,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -528,15 +526,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -546,7 +538,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -670,11 +662,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1207,7 +1196,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index 38f9ffcd04f..c0f6217caa6 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23245,9 +23245,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23379,18 +23377,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23427,11 +23416,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index a4abb29cf64..8922d713916 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index b4d5abbaca7..90234c3f736 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1325,6 +1325,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v01-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-06-16 11:54 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-06-16 11:54 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 9407c357f27..fa5a53d04ff 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 9ab74c8df0a..2af586669ae 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -689,6 +689,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1376,22 +1378,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1408,9 +1404,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1495,9 +1489,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1524,7 +1516,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1537,8 +1529,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -3926,27 +3918,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4034,11 +4018,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 2debadd86ed..28b34fd4387 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -503,13 +503,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -528,15 +526,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -546,7 +538,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -670,11 +662,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1207,7 +1196,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index 38f9ffcd04f..c0f6217caa6 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23245,9 +23245,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23379,18 +23377,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23427,11 +23416,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index a4abb29cf64..8922d713916 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index b4d5abbaca7..90234c3f736 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1325,6 +1325,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v01-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-06-16 11:54 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-06-16 11:54 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 9407c357f27..fa5a53d04ff 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 9ab74c8df0a..2af586669ae 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -689,6 +689,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1376,22 +1378,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1408,9 +1404,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1495,9 +1489,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1524,7 +1516,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1537,8 +1529,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -3926,27 +3918,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4034,11 +4018,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 2debadd86ed..28b34fd4387 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -503,13 +503,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -528,15 +526,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -546,7 +538,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -670,11 +662,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1207,7 +1196,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index 38f9ffcd04f..c0f6217caa6 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23245,9 +23245,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23379,18 +23377,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23427,11 +23416,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index a4abb29cf64..8922d713916 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index b4d5abbaca7..90234c3f736 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1325,6 +1325,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v01-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-06-16 11:54 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-06-16 11:54 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 9407c357f27..fa5a53d04ff 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 9ab74c8df0a..2af586669ae 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -689,6 +689,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1376,22 +1378,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1408,9 +1404,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1495,9 +1489,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1524,7 +1516,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1537,8 +1529,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -3926,27 +3918,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4034,11 +4018,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 2debadd86ed..28b34fd4387 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -503,13 +503,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -528,15 +526,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -546,7 +538,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -670,11 +662,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1207,7 +1196,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index 38f9ffcd04f..c0f6217caa6 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23245,9 +23245,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23379,18 +23377,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23427,11 +23416,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index a4abb29cf64..8922d713916 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index b4d5abbaca7..90234c3f736 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1325,6 +1325,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v01-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-06-16 11:54 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-06-16 11:54 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 9407c357f27..fa5a53d04ff 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 9ab74c8df0a..2af586669ae 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -689,6 +689,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1376,22 +1378,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1408,9 +1404,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1495,9 +1489,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1524,7 +1516,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1537,8 +1529,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -3926,27 +3918,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4034,11 +4018,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 2debadd86ed..28b34fd4387 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -503,13 +503,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -528,15 +526,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -546,7 +538,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -670,11 +662,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1207,7 +1196,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index 38f9ffcd04f..c0f6217caa6 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23245,9 +23245,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23379,18 +23377,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23427,11 +23416,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index a4abb29cf64..8922d713916 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index b4d5abbaca7..90234c3f736 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1325,6 +1325,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v01-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-06-16 11:54 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-06-16 11:54 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 9407c357f27..fa5a53d04ff 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 9ab74c8df0a..2af586669ae 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -689,6 +689,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1376,22 +1378,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1408,9 +1404,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1495,9 +1489,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1524,7 +1516,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1537,8 +1529,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -3926,27 +3918,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4034,11 +4018,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 2debadd86ed..28b34fd4387 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -503,13 +503,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -528,15 +526,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -546,7 +538,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -670,11 +662,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1207,7 +1196,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index 38f9ffcd04f..c0f6217caa6 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23245,9 +23245,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23379,18 +23377,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23427,11 +23416,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index a4abb29cf64..8922d713916 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index b4d5abbaca7..90234c3f736 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1325,6 +1325,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v01-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-06-16 11:54 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-06-16 11:54 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 9407c357f27..fa5a53d04ff 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 9ab74c8df0a..2af586669ae 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -689,6 +689,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1376,22 +1378,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1408,9 +1404,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1495,9 +1489,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1524,7 +1516,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1537,8 +1529,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -3926,27 +3918,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4034,11 +4018,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 2debadd86ed..28b34fd4387 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -503,13 +503,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -528,15 +526,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -546,7 +538,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -670,11 +662,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1207,7 +1196,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index 38f9ffcd04f..c0f6217caa6 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23245,9 +23245,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23379,18 +23377,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23427,11 +23416,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index a4abb29cf64..8922d713916 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index b4d5abbaca7..90234c3f736 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1325,6 +1325,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v01-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-06-16 11:54 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-06-16 11:54 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 9407c357f27..fa5a53d04ff 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 9ab74c8df0a..2af586669ae 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -689,6 +689,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1376,22 +1378,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1408,9 +1404,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1495,9 +1489,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1524,7 +1516,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1537,8 +1529,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -3926,27 +3918,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4034,11 +4018,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 2debadd86ed..28b34fd4387 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -503,13 +503,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -528,15 +526,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -546,7 +538,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -670,11 +662,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1207,7 +1196,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index 38f9ffcd04f..c0f6217caa6 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23245,9 +23245,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23379,18 +23377,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23427,11 +23416,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index a4abb29cf64..8922d713916 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index b4d5abbaca7..90234c3f736 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1325,6 +1325,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v01-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-06-16 11:54 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-06-16 11:54 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 9407c357f27..fa5a53d04ff 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 9ab74c8df0a..2af586669ae 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -689,6 +689,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1376,22 +1378,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1408,9 +1404,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1495,9 +1489,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1524,7 +1516,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1537,8 +1529,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -3926,27 +3918,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4034,11 +4018,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 2debadd86ed..28b34fd4387 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -503,13 +503,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -528,15 +526,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -546,7 +538,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -670,11 +662,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1207,7 +1196,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index 38f9ffcd04f..c0f6217caa6 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23245,9 +23245,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23379,18 +23377,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23427,11 +23416,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index a4abb29cf64..8922d713916 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index b4d5abbaca7..90234c3f736 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1325,6 +1325,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v01-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-06-16 11:54 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-06-16 11:54 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 9407c357f27..fa5a53d04ff 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 9ab74c8df0a..2af586669ae 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -689,6 +689,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1376,22 +1378,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1408,9 +1404,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1495,9 +1489,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1524,7 +1516,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1537,8 +1529,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -3926,27 +3918,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4034,11 +4018,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 2debadd86ed..28b34fd4387 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -503,13 +503,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -528,15 +526,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -546,7 +538,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -670,11 +662,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1207,7 +1196,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index 38f9ffcd04f..c0f6217caa6 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23245,9 +23245,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23379,18 +23377,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23427,11 +23416,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index a4abb29cf64..8922d713916 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index b4d5abbaca7..90234c3f736 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1325,6 +1325,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v01-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-06-16 11:54 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-06-16 11:54 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 9407c357f27..fa5a53d04ff 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 9ab74c8df0a..2af586669ae 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -689,6 +689,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1376,22 +1378,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1408,9 +1404,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1495,9 +1489,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1524,7 +1516,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1537,8 +1529,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -3926,27 +3918,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4034,11 +4018,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 2debadd86ed..28b34fd4387 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -503,13 +503,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -528,15 +526,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -546,7 +538,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -670,11 +662,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1207,7 +1196,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index 38f9ffcd04f..c0f6217caa6 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23245,9 +23245,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23379,18 +23377,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23427,11 +23416,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index a4abb29cf64..8922d713916 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index b4d5abbaca7..90234c3f736 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1325,6 +1325,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v01-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-06-16 11:54 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-06-16 11:54 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 9407c357f27..fa5a53d04ff 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 9ab74c8df0a..2af586669ae 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -689,6 +689,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1376,22 +1378,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1408,9 +1404,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1495,9 +1489,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1524,7 +1516,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1537,8 +1529,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -3926,27 +3918,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4034,11 +4018,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 2debadd86ed..28b34fd4387 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -503,13 +503,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -528,15 +526,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -546,7 +538,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -670,11 +662,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1207,7 +1196,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index 38f9ffcd04f..c0f6217caa6 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23245,9 +23245,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23379,18 +23377,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23427,11 +23416,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index a4abb29cf64..8922d713916 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index b4d5abbaca7..90234c3f736 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1325,6 +1325,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v01-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-06-16 11:54 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-06-16 11:54 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 9407c357f27..fa5a53d04ff 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 9ab74c8df0a..2af586669ae 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -689,6 +689,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1376,22 +1378,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1408,9 +1404,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1495,9 +1489,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1524,7 +1516,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1537,8 +1529,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -3926,27 +3918,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4034,11 +4018,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 2debadd86ed..28b34fd4387 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -503,13 +503,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -528,15 +526,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -546,7 +538,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -670,11 +662,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1207,7 +1196,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index 38f9ffcd04f..c0f6217caa6 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23245,9 +23245,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23379,18 +23377,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23427,11 +23416,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index a4abb29cf64..8922d713916 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index b4d5abbaca7..90234c3f736 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1325,6 +1325,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v01-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-06-16 11:54 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-06-16 11:54 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 9407c357f27..fa5a53d04ff 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 9ab74c8df0a..2af586669ae 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -689,6 +689,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1376,22 +1378,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1408,9 +1404,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1495,9 +1489,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1524,7 +1516,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1537,8 +1529,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -3926,27 +3918,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4034,11 +4018,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 2debadd86ed..28b34fd4387 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -503,13 +503,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -528,15 +526,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -546,7 +538,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -670,11 +662,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1207,7 +1196,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index 38f9ffcd04f..c0f6217caa6 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23245,9 +23245,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23379,18 +23377,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23427,11 +23416,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index a4abb29cf64..8922d713916 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index b4d5abbaca7..90234c3f736 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1325,6 +1325,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v01-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-06-16 11:54 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-06-16 11:54 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 9407c357f27..fa5a53d04ff 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 9ab74c8df0a..2af586669ae 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -689,6 +689,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1376,22 +1378,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1408,9 +1404,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1495,9 +1489,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1524,7 +1516,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1537,8 +1529,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -3926,27 +3918,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4034,11 +4018,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 2debadd86ed..28b34fd4387 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -503,13 +503,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -528,15 +526,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -546,7 +538,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -670,11 +662,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1207,7 +1196,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index 38f9ffcd04f..c0f6217caa6 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23245,9 +23245,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23379,18 +23377,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23427,11 +23416,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index a4abb29cf64..8922d713916 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index b4d5abbaca7..90234c3f736 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1325,6 +1325,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v01-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-06-16 11:54 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-06-16 11:54 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 9407c357f27..fa5a53d04ff 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 9ab74c8df0a..2af586669ae 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -689,6 +689,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1376,22 +1378,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1408,9 +1404,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1495,9 +1489,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1524,7 +1516,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1537,8 +1529,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -3926,27 +3918,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4034,11 +4018,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 2debadd86ed..28b34fd4387 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -503,13 +503,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -528,15 +526,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -546,7 +538,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -670,11 +662,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1207,7 +1196,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index 38f9ffcd04f..c0f6217caa6 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23245,9 +23245,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23379,18 +23377,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23427,11 +23416,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index a4abb29cf64..8922d713916 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index b4d5abbaca7..90234c3f736 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1325,6 +1325,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v01-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-06-16 11:54 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-06-16 11:54 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 9407c357f27..fa5a53d04ff 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 9ab74c8df0a..2af586669ae 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -689,6 +689,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1376,22 +1378,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1408,9 +1404,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1495,9 +1489,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1524,7 +1516,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1537,8 +1529,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -3926,27 +3918,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4034,11 +4018,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 2debadd86ed..28b34fd4387 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -503,13 +503,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -528,15 +526,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -546,7 +538,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -670,11 +662,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1207,7 +1196,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index 38f9ffcd04f..c0f6217caa6 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23245,9 +23245,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23379,18 +23377,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23427,11 +23416,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index a4abb29cf64..8922d713916 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index b4d5abbaca7..90234c3f736 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1325,6 +1325,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v01-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-06-16 11:54 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-06-16 11:54 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 9407c357f27..fa5a53d04ff 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 9ab74c8df0a..2af586669ae 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -689,6 +689,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1376,22 +1378,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1408,9 +1404,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1495,9 +1489,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1524,7 +1516,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1537,8 +1529,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -3926,27 +3918,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4034,11 +4018,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 2debadd86ed..28b34fd4387 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -503,13 +503,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -528,15 +526,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -546,7 +538,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -670,11 +662,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1207,7 +1196,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index 38f9ffcd04f..c0f6217caa6 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23245,9 +23245,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23379,18 +23377,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23427,11 +23416,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index a4abb29cf64..8922d713916 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index b4d5abbaca7..90234c3f736 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1325,6 +1325,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v01-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-06-16 11:54 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-06-16 11:54 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 9407c357f27..fa5a53d04ff 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 9ab74c8df0a..2af586669ae 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -689,6 +689,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1376,22 +1378,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1408,9 +1404,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1495,9 +1489,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1524,7 +1516,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1537,8 +1529,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -3926,27 +3918,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4034,11 +4018,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 2debadd86ed..28b34fd4387 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -503,13 +503,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -528,15 +526,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -546,7 +538,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -670,11 +662,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1207,7 +1196,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index 38f9ffcd04f..c0f6217caa6 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23245,9 +23245,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23379,18 +23377,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23427,11 +23416,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index a4abb29cf64..8922d713916 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index b4d5abbaca7..90234c3f736 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1325,6 +1325,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v01-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-06-16 11:54 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-06-16 11:54 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 9407c357f27..fa5a53d04ff 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 9ab74c8df0a..2af586669ae 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -689,6 +689,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1376,22 +1378,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1408,9 +1404,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1495,9 +1489,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1524,7 +1516,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1537,8 +1529,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -3926,27 +3918,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4034,11 +4018,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 2debadd86ed..28b34fd4387 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -503,13 +503,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -528,15 +526,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -546,7 +538,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -670,11 +662,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1207,7 +1196,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index 38f9ffcd04f..c0f6217caa6 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23245,9 +23245,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23379,18 +23377,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23427,11 +23416,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index a4abb29cf64..8922d713916 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index b4d5abbaca7..90234c3f736 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1325,6 +1325,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v01-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-06-16 11:54 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-06-16 11:54 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 9407c357f27..fa5a53d04ff 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 9ab74c8df0a..2af586669ae 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -689,6 +689,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1376,22 +1378,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1408,9 +1404,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1495,9 +1489,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1524,7 +1516,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1537,8 +1529,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -3926,27 +3918,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4034,11 +4018,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 2debadd86ed..28b34fd4387 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -503,13 +503,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -528,15 +526,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -546,7 +538,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -670,11 +662,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1207,7 +1196,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index 38f9ffcd04f..c0f6217caa6 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23245,9 +23245,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23379,18 +23377,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23427,11 +23416,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index a4abb29cf64..8922d713916 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index b4d5abbaca7..90234c3f736 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1325,6 +1325,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v01-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-06-16 11:54 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-06-16 11:54 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 9407c357f27..fa5a53d04ff 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 9ab74c8df0a..2af586669ae 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -689,6 +689,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1376,22 +1378,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1408,9 +1404,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1495,9 +1489,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1524,7 +1516,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1537,8 +1529,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -3926,27 +3918,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4034,11 +4018,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 2debadd86ed..28b34fd4387 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -503,13 +503,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -528,15 +526,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -546,7 +538,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -670,11 +662,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1207,7 +1196,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index 38f9ffcd04f..c0f6217caa6 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23245,9 +23245,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23379,18 +23377,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23427,11 +23416,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index a4abb29cf64..8922d713916 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index b4d5abbaca7..90234c3f736 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1325,6 +1325,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v01-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-06-16 11:54 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-06-16 11:54 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 9407c357f27..fa5a53d04ff 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 9ab74c8df0a..2af586669ae 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -689,6 +689,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1376,22 +1378,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1408,9 +1404,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1495,9 +1489,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1524,7 +1516,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1537,8 +1529,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -3926,27 +3918,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4034,11 +4018,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 2debadd86ed..28b34fd4387 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -503,13 +503,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -528,15 +526,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -546,7 +538,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -670,11 +662,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1207,7 +1196,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index 38f9ffcd04f..c0f6217caa6 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23245,9 +23245,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23379,18 +23377,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23427,11 +23416,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index a4abb29cf64..8922d713916 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index b4d5abbaca7..90234c3f736 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1325,6 +1325,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v01-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-06-16 11:54 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-06-16 11:54 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 9407c357f27..fa5a53d04ff 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 9ab74c8df0a..2af586669ae 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -689,6 +689,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1376,22 +1378,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1408,9 +1404,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1495,9 +1489,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1524,7 +1516,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1537,8 +1529,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -3926,27 +3918,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4034,11 +4018,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 2debadd86ed..28b34fd4387 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -503,13 +503,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -528,15 +526,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -546,7 +538,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -670,11 +662,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1207,7 +1196,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index 38f9ffcd04f..c0f6217caa6 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23245,9 +23245,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23379,18 +23377,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23427,11 +23416,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index a4abb29cf64..8922d713916 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index b4d5abbaca7..90234c3f736 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1325,6 +1325,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v01-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-06-16 11:54 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-06-16 11:54 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 9407c357f27..fa5a53d04ff 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 9ab74c8df0a..2af586669ae 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -689,6 +689,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1376,22 +1378,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1408,9 +1404,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1495,9 +1489,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1524,7 +1516,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1537,8 +1529,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -3926,27 +3918,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4034,11 +4018,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 2debadd86ed..28b34fd4387 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -503,13 +503,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -528,15 +526,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -546,7 +538,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -670,11 +662,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1207,7 +1196,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index 38f9ffcd04f..c0f6217caa6 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23245,9 +23245,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23379,18 +23377,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23427,11 +23416,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index a4abb29cf64..8922d713916 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index b4d5abbaca7..90234c3f736 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1325,6 +1325,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v01-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-06-16 11:54 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-06-16 11:54 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 9407c357f27..fa5a53d04ff 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 9ab74c8df0a..2af586669ae 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -689,6 +689,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1376,22 +1378,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1408,9 +1404,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1495,9 +1489,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1524,7 +1516,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1537,8 +1529,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -3926,27 +3918,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4034,11 +4018,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 2debadd86ed..28b34fd4387 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -503,13 +503,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -528,15 +526,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -546,7 +538,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -670,11 +662,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1207,7 +1196,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index 38f9ffcd04f..c0f6217caa6 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23245,9 +23245,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23379,18 +23377,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23427,11 +23416,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index a4abb29cf64..8922d713916 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index b4d5abbaca7..90234c3f736 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1325,6 +1325,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v01-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-06-16 11:54 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-06-16 11:54 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 9407c357f27..fa5a53d04ff 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 9ab74c8df0a..2af586669ae 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -689,6 +689,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1376,22 +1378,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1408,9 +1404,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1495,9 +1489,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1524,7 +1516,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1537,8 +1529,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -3926,27 +3918,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4034,11 +4018,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 2debadd86ed..28b34fd4387 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -503,13 +503,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -528,15 +526,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -546,7 +538,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -670,11 +662,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1207,7 +1196,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index 38f9ffcd04f..c0f6217caa6 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23245,9 +23245,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23379,18 +23377,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23427,11 +23416,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index a4abb29cf64..8922d713916 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index b4d5abbaca7..90234c3f736 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1325,6 +1325,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v01-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-06-16 11:54 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-06-16 11:54 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 9407c357f27..fa5a53d04ff 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 9ab74c8df0a..2af586669ae 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -689,6 +689,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1376,22 +1378,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1408,9 +1404,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1495,9 +1489,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1524,7 +1516,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1537,8 +1529,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -3926,27 +3918,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4034,11 +4018,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 2debadd86ed..28b34fd4387 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -503,13 +503,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -528,15 +526,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -546,7 +538,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -670,11 +662,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1207,7 +1196,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index 38f9ffcd04f..c0f6217caa6 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23245,9 +23245,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23379,18 +23377,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23427,11 +23416,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index a4abb29cf64..8922d713916 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index b4d5abbaca7..90234c3f736 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1325,6 +1325,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v01-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-06-16 11:54 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-06-16 11:54 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 9407c357f27..fa5a53d04ff 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 9ab74c8df0a..2af586669ae 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -689,6 +689,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1376,22 +1378,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1408,9 +1404,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1495,9 +1489,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1524,7 +1516,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1537,8 +1529,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -3926,27 +3918,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4034,11 +4018,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 2debadd86ed..28b34fd4387 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -503,13 +503,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -528,15 +526,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -546,7 +538,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -670,11 +662,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1207,7 +1196,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index 38f9ffcd04f..c0f6217caa6 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23245,9 +23245,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23379,18 +23377,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23427,11 +23416,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index a4abb29cf64..8922d713916 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index b4d5abbaca7..90234c3f736 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1325,6 +1325,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v01-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-06-16 11:54 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-06-16 11:54 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 9407c357f27..fa5a53d04ff 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 9ab74c8df0a..2af586669ae 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -689,6 +689,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1376,22 +1378,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1408,9 +1404,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1495,9 +1489,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1524,7 +1516,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1537,8 +1529,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -3926,27 +3918,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4034,11 +4018,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 2debadd86ed..28b34fd4387 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -503,13 +503,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -528,15 +526,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -546,7 +538,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -670,11 +662,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1207,7 +1196,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index 38f9ffcd04f..c0f6217caa6 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23245,9 +23245,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23379,18 +23377,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23427,11 +23416,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index a4abb29cf64..8922d713916 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index b4d5abbaca7..90234c3f736 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1325,6 +1325,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v01-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-06-16 11:54 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-06-16 11:54 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 9407c357f27..fa5a53d04ff 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 9ab74c8df0a..2af586669ae 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -689,6 +689,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1376,22 +1378,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1408,9 +1404,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1495,9 +1489,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1524,7 +1516,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1537,8 +1529,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -3926,27 +3918,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4034,11 +4018,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 2debadd86ed..28b34fd4387 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -503,13 +503,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -528,15 +526,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -546,7 +538,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -670,11 +662,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1207,7 +1196,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index 38f9ffcd04f..c0f6217caa6 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23245,9 +23245,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23379,18 +23377,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23427,11 +23416,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index a4abb29cf64..8922d713916 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index b4d5abbaca7..90234c3f736 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1325,6 +1325,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v01-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-06-16 11:54 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-06-16 11:54 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 9407c357f27..fa5a53d04ff 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 9ab74c8df0a..2af586669ae 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -689,6 +689,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1376,22 +1378,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1408,9 +1404,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1495,9 +1489,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1524,7 +1516,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1537,8 +1529,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -3926,27 +3918,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4034,11 +4018,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 2debadd86ed..28b34fd4387 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -503,13 +503,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -528,15 +526,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -546,7 +538,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -670,11 +662,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1207,7 +1196,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index 38f9ffcd04f..c0f6217caa6 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23245,9 +23245,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23379,18 +23377,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23427,11 +23416,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index a4abb29cf64..8922d713916 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index b4d5abbaca7..90234c3f736 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1325,6 +1325,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v01-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-06-16 11:54 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-06-16 11:54 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 9407c357f27..fa5a53d04ff 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 9ab74c8df0a..2af586669ae 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -689,6 +689,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1376,22 +1378,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1408,9 +1404,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1495,9 +1489,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1524,7 +1516,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1537,8 +1529,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -3926,27 +3918,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4034,11 +4018,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 2debadd86ed..28b34fd4387 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -503,13 +503,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -528,15 +526,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -546,7 +538,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -670,11 +662,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1207,7 +1196,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index 38f9ffcd04f..c0f6217caa6 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23245,9 +23245,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23379,18 +23377,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23427,11 +23416,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index a4abb29cf64..8922d713916 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index b4d5abbaca7..90234c3f736 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1325,6 +1325,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v01-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-06-16 11:54 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-06-16 11:54 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 9407c357f27..fa5a53d04ff 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 9ab74c8df0a..2af586669ae 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -689,6 +689,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1376,22 +1378,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1408,9 +1404,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1495,9 +1489,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1524,7 +1516,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1537,8 +1529,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -3926,27 +3918,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4034,11 +4018,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 2debadd86ed..28b34fd4387 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -503,13 +503,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -528,15 +526,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -546,7 +538,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -670,11 +662,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1207,7 +1196,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index 38f9ffcd04f..c0f6217caa6 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23245,9 +23245,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23379,18 +23377,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23427,11 +23416,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index a4abb29cf64..8922d713916 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index b4d5abbaca7..90234c3f736 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1325,6 +1325,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v01-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-06-16 11:54 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-06-16 11:54 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 9407c357f27..fa5a53d04ff 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 9ab74c8df0a..2af586669ae 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -689,6 +689,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1376,22 +1378,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1408,9 +1404,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1495,9 +1489,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1524,7 +1516,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1537,8 +1529,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -3926,27 +3918,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4034,11 +4018,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 2debadd86ed..28b34fd4387 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -503,13 +503,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -528,15 +526,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -546,7 +538,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -670,11 +662,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1207,7 +1196,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index 38f9ffcd04f..c0f6217caa6 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23245,9 +23245,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23379,18 +23377,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23427,11 +23416,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index a4abb29cf64..8922d713916 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index b4d5abbaca7..90234c3f736 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1325,6 +1325,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v01-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-06-16 11:54 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-06-16 11:54 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 9407c357f27..fa5a53d04ff 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 9ab74c8df0a..2af586669ae 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -689,6 +689,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1376,22 +1378,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1408,9 +1404,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1495,9 +1489,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1524,7 +1516,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1537,8 +1529,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -3926,27 +3918,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4034,11 +4018,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 2debadd86ed..28b34fd4387 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -503,13 +503,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -528,15 +526,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -546,7 +538,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -670,11 +662,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1207,7 +1196,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index 38f9ffcd04f..c0f6217caa6 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23245,9 +23245,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23379,18 +23377,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23427,11 +23416,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index a4abb29cf64..8922d713916 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index b4d5abbaca7..90234c3f736 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1325,6 +1325,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v01-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-06-16 11:54 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-06-16 11:54 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 9407c357f27..fa5a53d04ff 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 9ab74c8df0a..2af586669ae 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -689,6 +689,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1376,22 +1378,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1408,9 +1404,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1495,9 +1489,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1524,7 +1516,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1537,8 +1529,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -3926,27 +3918,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4034,11 +4018,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 2debadd86ed..28b34fd4387 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -503,13 +503,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -528,15 +526,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -546,7 +538,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -670,11 +662,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1207,7 +1196,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index 38f9ffcd04f..c0f6217caa6 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23245,9 +23245,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23379,18 +23377,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23427,11 +23416,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index a4abb29cf64..8922d713916 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index b4d5abbaca7..90234c3f736 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1325,6 +1325,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v01-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-06-16 11:54 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-06-16 11:54 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 9407c357f27..fa5a53d04ff 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 9ab74c8df0a..2af586669ae 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -689,6 +689,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1376,22 +1378,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1408,9 +1404,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1495,9 +1489,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1524,7 +1516,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1537,8 +1529,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -3926,27 +3918,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4034,11 +4018,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 2debadd86ed..28b34fd4387 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -503,13 +503,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -528,15 +526,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -546,7 +538,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -670,11 +662,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1207,7 +1196,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index 38f9ffcd04f..c0f6217caa6 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23245,9 +23245,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23379,18 +23377,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23427,11 +23416,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index a4abb29cf64..8922d713916 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index b4d5abbaca7..90234c3f736 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1325,6 +1325,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v01-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-07-15 08:37 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-07-15 08:37 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 81bba4beac7..8eabe232d1e 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 713bb5d10f1..5bc28c94139 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -699,6 +699,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1386,22 +1388,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1418,9 +1414,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1505,9 +1499,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1534,7 +1526,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1547,8 +1539,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -4051,27 +4043,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4159,11 +4143,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 0bf19d07db5..1ad453a39a0 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -514,13 +514,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -539,15 +537,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -557,7 +549,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -681,11 +673,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1234,7 +1223,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index cb93c3e935a..d691b317011 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23762,9 +23762,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23896,18 +23894,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23944,11 +23933,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index 38539a6fd3d..5d1cbc382fa 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index 25ac7079099..0ec534d15d7 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1327,6 +1327,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v02-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-07-15 08:37 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-07-15 08:37 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 81bba4beac7..8eabe232d1e 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 713bb5d10f1..5bc28c94139 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -699,6 +699,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1386,22 +1388,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1418,9 +1414,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1505,9 +1499,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1534,7 +1526,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1547,8 +1539,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -4051,27 +4043,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4159,11 +4143,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 0bf19d07db5..1ad453a39a0 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -514,13 +514,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -539,15 +537,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -557,7 +549,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -681,11 +673,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1234,7 +1223,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index cb93c3e935a..d691b317011 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23762,9 +23762,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23896,18 +23894,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23944,11 +23933,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index 38539a6fd3d..5d1cbc382fa 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index 25ac7079099..0ec534d15d7 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1327,6 +1327,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v02-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-07-15 08:37 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-07-15 08:37 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 81bba4beac7..8eabe232d1e 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 713bb5d10f1..5bc28c94139 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -699,6 +699,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1386,22 +1388,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1418,9 +1414,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1505,9 +1499,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1534,7 +1526,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1547,8 +1539,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -4051,27 +4043,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4159,11 +4143,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 0bf19d07db5..1ad453a39a0 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -514,13 +514,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -539,15 +537,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -557,7 +549,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -681,11 +673,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1234,7 +1223,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index cb93c3e935a..d691b317011 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23762,9 +23762,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23896,18 +23894,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23944,11 +23933,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index 38539a6fd3d..5d1cbc382fa 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index 25ac7079099..0ec534d15d7 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1327,6 +1327,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v02-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-07-15 08:37 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-07-15 08:37 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 81bba4beac7..8eabe232d1e 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 713bb5d10f1..5bc28c94139 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -699,6 +699,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1386,22 +1388,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1418,9 +1414,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1505,9 +1499,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1534,7 +1526,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1547,8 +1539,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -4051,27 +4043,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4159,11 +4143,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 0bf19d07db5..1ad453a39a0 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -514,13 +514,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -539,15 +537,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -557,7 +549,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -681,11 +673,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1234,7 +1223,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index cb93c3e935a..d691b317011 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23762,9 +23762,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23896,18 +23894,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23944,11 +23933,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index 38539a6fd3d..5d1cbc382fa 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index 25ac7079099..0ec534d15d7 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1327,6 +1327,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v02-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-07-15 08:37 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-07-15 08:37 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 81bba4beac7..8eabe232d1e 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 713bb5d10f1..5bc28c94139 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -699,6 +699,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1386,22 +1388,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1418,9 +1414,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1505,9 +1499,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1534,7 +1526,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1547,8 +1539,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -4051,27 +4043,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4159,11 +4143,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 0bf19d07db5..1ad453a39a0 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -514,13 +514,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -539,15 +537,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -557,7 +549,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -681,11 +673,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1234,7 +1223,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index cb93c3e935a..d691b317011 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23762,9 +23762,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23896,18 +23894,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23944,11 +23933,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index 38539a6fd3d..5d1cbc382fa 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index 25ac7079099..0ec534d15d7 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1327,6 +1327,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v02-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-07-15 08:37 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-07-15 08:37 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 81bba4beac7..8eabe232d1e 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 713bb5d10f1..5bc28c94139 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -699,6 +699,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1386,22 +1388,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1418,9 +1414,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1505,9 +1499,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1534,7 +1526,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1547,8 +1539,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -4051,27 +4043,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4159,11 +4143,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 0bf19d07db5..1ad453a39a0 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -514,13 +514,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -539,15 +537,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -557,7 +549,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -681,11 +673,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1234,7 +1223,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index cb93c3e935a..d691b317011 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23762,9 +23762,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23896,18 +23894,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23944,11 +23933,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index 38539a6fd3d..5d1cbc382fa 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index 25ac7079099..0ec534d15d7 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1327,6 +1327,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v02-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-07-15 08:37 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-07-15 08:37 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 81bba4beac7..8eabe232d1e 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 713bb5d10f1..5bc28c94139 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -699,6 +699,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1386,22 +1388,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1418,9 +1414,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1505,9 +1499,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1534,7 +1526,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1547,8 +1539,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -4051,27 +4043,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4159,11 +4143,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 0bf19d07db5..1ad453a39a0 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -514,13 +514,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -539,15 +537,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -557,7 +549,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -681,11 +673,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1234,7 +1223,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index cb93c3e935a..d691b317011 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23762,9 +23762,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23896,18 +23894,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23944,11 +23933,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index 38539a6fd3d..5d1cbc382fa 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index 25ac7079099..0ec534d15d7 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1327,6 +1327,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v02-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-07-15 08:37 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-07-15 08:37 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 81bba4beac7..8eabe232d1e 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 713bb5d10f1..5bc28c94139 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -699,6 +699,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1386,22 +1388,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1418,9 +1414,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1505,9 +1499,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1534,7 +1526,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1547,8 +1539,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -4051,27 +4043,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4159,11 +4143,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 0bf19d07db5..1ad453a39a0 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -514,13 +514,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -539,15 +537,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -557,7 +549,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -681,11 +673,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1234,7 +1223,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index cb93c3e935a..d691b317011 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23762,9 +23762,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23896,18 +23894,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23944,11 +23933,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index 38539a6fd3d..5d1cbc382fa 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index 25ac7079099..0ec534d15d7 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1327,6 +1327,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v02-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-07-15 08:37 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-07-15 08:37 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 81bba4beac7..8eabe232d1e 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 713bb5d10f1..5bc28c94139 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -699,6 +699,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1386,22 +1388,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1418,9 +1414,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1505,9 +1499,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1534,7 +1526,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1547,8 +1539,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -4051,27 +4043,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4159,11 +4143,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 0bf19d07db5..1ad453a39a0 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -514,13 +514,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -539,15 +537,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -557,7 +549,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -681,11 +673,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1234,7 +1223,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index cb93c3e935a..d691b317011 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23762,9 +23762,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23896,18 +23894,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23944,11 +23933,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index 38539a6fd3d..5d1cbc382fa 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index 25ac7079099..0ec534d15d7 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1327,6 +1327,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v02-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-07-15 08:37 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-07-15 08:37 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 81bba4beac7..8eabe232d1e 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 713bb5d10f1..5bc28c94139 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -699,6 +699,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1386,22 +1388,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1418,9 +1414,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1505,9 +1499,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1534,7 +1526,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1547,8 +1539,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -4051,27 +4043,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4159,11 +4143,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 0bf19d07db5..1ad453a39a0 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -514,13 +514,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -539,15 +537,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -557,7 +549,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -681,11 +673,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1234,7 +1223,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index cb93c3e935a..d691b317011 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23762,9 +23762,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23896,18 +23894,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23944,11 +23933,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index 38539a6fd3d..5d1cbc382fa 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index 25ac7079099..0ec534d15d7 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1327,6 +1327,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v02-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-07-15 08:37 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-07-15 08:37 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 81bba4beac7..8eabe232d1e 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 713bb5d10f1..5bc28c94139 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -699,6 +699,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1386,22 +1388,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1418,9 +1414,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1505,9 +1499,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1534,7 +1526,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1547,8 +1539,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -4051,27 +4043,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4159,11 +4143,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 0bf19d07db5..1ad453a39a0 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -514,13 +514,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -539,15 +537,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -557,7 +549,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -681,11 +673,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1234,7 +1223,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index cb93c3e935a..d691b317011 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23762,9 +23762,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23896,18 +23894,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23944,11 +23933,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index 38539a6fd3d..5d1cbc382fa 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index 25ac7079099..0ec534d15d7 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1327,6 +1327,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v02-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-07-15 08:37 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-07-15 08:37 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 81bba4beac7..8eabe232d1e 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 713bb5d10f1..5bc28c94139 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -699,6 +699,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1386,22 +1388,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1418,9 +1414,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1505,9 +1499,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1534,7 +1526,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1547,8 +1539,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -4051,27 +4043,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4159,11 +4143,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 0bf19d07db5..1ad453a39a0 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -514,13 +514,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -539,15 +537,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -557,7 +549,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -681,11 +673,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1234,7 +1223,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index cb93c3e935a..d691b317011 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23762,9 +23762,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23896,18 +23894,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23944,11 +23933,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index 38539a6fd3d..5d1cbc382fa 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index 25ac7079099..0ec534d15d7 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1327,6 +1327,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v02-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-07-15 08:37 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-07-15 08:37 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 81bba4beac7..8eabe232d1e 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 713bb5d10f1..5bc28c94139 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -699,6 +699,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1386,22 +1388,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1418,9 +1414,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1505,9 +1499,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1534,7 +1526,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1547,8 +1539,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -4051,27 +4043,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4159,11 +4143,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 0bf19d07db5..1ad453a39a0 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -514,13 +514,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -539,15 +537,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -557,7 +549,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -681,11 +673,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1234,7 +1223,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index cb93c3e935a..d691b317011 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23762,9 +23762,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23896,18 +23894,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23944,11 +23933,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index 38539a6fd3d..5d1cbc382fa 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index 25ac7079099..0ec534d15d7 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1327,6 +1327,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v02-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-07-15 08:37 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-07-15 08:37 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 81bba4beac7..8eabe232d1e 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 713bb5d10f1..5bc28c94139 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -699,6 +699,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1386,22 +1388,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1418,9 +1414,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1505,9 +1499,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1534,7 +1526,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1547,8 +1539,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -4051,27 +4043,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4159,11 +4143,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 0bf19d07db5..1ad453a39a0 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -514,13 +514,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -539,15 +537,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -557,7 +549,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -681,11 +673,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1234,7 +1223,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index cb93c3e935a..d691b317011 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23762,9 +23762,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23896,18 +23894,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23944,11 +23933,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index 38539a6fd3d..5d1cbc382fa 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index 25ac7079099..0ec534d15d7 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1327,6 +1327,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v02-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-07-15 08:37 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-07-15 08:37 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 81bba4beac7..8eabe232d1e 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 713bb5d10f1..5bc28c94139 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -699,6 +699,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1386,22 +1388,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1418,9 +1414,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1505,9 +1499,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1534,7 +1526,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1547,8 +1539,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -4051,27 +4043,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4159,11 +4143,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 0bf19d07db5..1ad453a39a0 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -514,13 +514,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -539,15 +537,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -557,7 +549,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -681,11 +673,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1234,7 +1223,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index cb93c3e935a..d691b317011 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23762,9 +23762,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23896,18 +23894,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23944,11 +23933,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index 38539a6fd3d..5d1cbc382fa 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index 25ac7079099..0ec534d15d7 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1327,6 +1327,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v02-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-07-15 08:37 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-07-15 08:37 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 81bba4beac7..8eabe232d1e 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 713bb5d10f1..5bc28c94139 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -699,6 +699,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1386,22 +1388,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1418,9 +1414,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1505,9 +1499,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1534,7 +1526,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1547,8 +1539,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -4051,27 +4043,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4159,11 +4143,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 0bf19d07db5..1ad453a39a0 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -514,13 +514,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -539,15 +537,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -557,7 +549,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -681,11 +673,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1234,7 +1223,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index cb93c3e935a..d691b317011 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23762,9 +23762,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23896,18 +23894,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23944,11 +23933,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index 38539a6fd3d..5d1cbc382fa 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index 25ac7079099..0ec534d15d7 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1327,6 +1327,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v02-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-07-15 08:37 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-07-15 08:37 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 81bba4beac7..8eabe232d1e 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 713bb5d10f1..5bc28c94139 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -699,6 +699,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1386,22 +1388,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1418,9 +1414,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1505,9 +1499,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1534,7 +1526,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1547,8 +1539,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -4051,27 +4043,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4159,11 +4143,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 0bf19d07db5..1ad453a39a0 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -514,13 +514,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -539,15 +537,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -557,7 +549,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -681,11 +673,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1234,7 +1223,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index cb93c3e935a..d691b317011 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23762,9 +23762,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23896,18 +23894,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23944,11 +23933,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index 38539a6fd3d..5d1cbc382fa 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index 25ac7079099..0ec534d15d7 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1327,6 +1327,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v02-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-07-15 08:37 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-07-15 08:37 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 81bba4beac7..8eabe232d1e 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 713bb5d10f1..5bc28c94139 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -699,6 +699,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1386,22 +1388,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1418,9 +1414,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1505,9 +1499,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1534,7 +1526,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1547,8 +1539,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -4051,27 +4043,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4159,11 +4143,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 0bf19d07db5..1ad453a39a0 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -514,13 +514,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -539,15 +537,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -557,7 +549,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -681,11 +673,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1234,7 +1223,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index cb93c3e935a..d691b317011 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23762,9 +23762,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23896,18 +23894,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23944,11 +23933,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index 38539a6fd3d..5d1cbc382fa 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index 25ac7079099..0ec534d15d7 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1327,6 +1327,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v02-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-07-15 08:37 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-07-15 08:37 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 81bba4beac7..8eabe232d1e 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 713bb5d10f1..5bc28c94139 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -699,6 +699,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1386,22 +1388,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1418,9 +1414,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1505,9 +1499,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1534,7 +1526,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1547,8 +1539,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -4051,27 +4043,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4159,11 +4143,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 0bf19d07db5..1ad453a39a0 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -514,13 +514,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -539,15 +537,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -557,7 +549,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -681,11 +673,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1234,7 +1223,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index cb93c3e935a..d691b317011 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23762,9 +23762,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23896,18 +23894,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23944,11 +23933,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index 38539a6fd3d..5d1cbc382fa 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index 25ac7079099..0ec534d15d7 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1327,6 +1327,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v02-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-07-15 08:37 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-07-15 08:37 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 81bba4beac7..8eabe232d1e 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 713bb5d10f1..5bc28c94139 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -699,6 +699,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1386,22 +1388,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1418,9 +1414,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1505,9 +1499,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1534,7 +1526,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1547,8 +1539,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -4051,27 +4043,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4159,11 +4143,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 0bf19d07db5..1ad453a39a0 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -514,13 +514,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -539,15 +537,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -557,7 +549,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -681,11 +673,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1234,7 +1223,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index cb93c3e935a..d691b317011 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23762,9 +23762,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23896,18 +23894,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23944,11 +23933,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index 38539a6fd3d..5d1cbc382fa 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index 25ac7079099..0ec534d15d7 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1327,6 +1327,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v02-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-07-15 08:37 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-07-15 08:37 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 81bba4beac7..8eabe232d1e 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 713bb5d10f1..5bc28c94139 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -699,6 +699,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1386,22 +1388,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1418,9 +1414,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1505,9 +1499,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1534,7 +1526,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1547,8 +1539,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -4051,27 +4043,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4159,11 +4143,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 0bf19d07db5..1ad453a39a0 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -514,13 +514,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -539,15 +537,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -557,7 +549,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -681,11 +673,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1234,7 +1223,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index cb93c3e935a..d691b317011 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23762,9 +23762,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23896,18 +23894,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23944,11 +23933,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index 38539a6fd3d..5d1cbc382fa 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index 25ac7079099..0ec534d15d7 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1327,6 +1327,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v02-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-07-15 08:37 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-07-15 08:37 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 81bba4beac7..8eabe232d1e 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 713bb5d10f1..5bc28c94139 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -699,6 +699,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1386,22 +1388,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1418,9 +1414,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1505,9 +1499,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1534,7 +1526,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1547,8 +1539,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -4051,27 +4043,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4159,11 +4143,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 0bf19d07db5..1ad453a39a0 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -514,13 +514,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -539,15 +537,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -557,7 +549,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -681,11 +673,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1234,7 +1223,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index cb93c3e935a..d691b317011 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23762,9 +23762,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23896,18 +23894,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23944,11 +23933,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index 38539a6fd3d..5d1cbc382fa 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index 25ac7079099..0ec534d15d7 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1327,6 +1327,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v02-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-07-15 08:37 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-07-15 08:37 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 81bba4beac7..8eabe232d1e 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 713bb5d10f1..5bc28c94139 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -699,6 +699,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1386,22 +1388,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1418,9 +1414,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1505,9 +1499,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1534,7 +1526,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1547,8 +1539,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -4051,27 +4043,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4159,11 +4143,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 0bf19d07db5..1ad453a39a0 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -514,13 +514,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -539,15 +537,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -557,7 +549,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -681,11 +673,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1234,7 +1223,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index cb93c3e935a..d691b317011 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23762,9 +23762,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23896,18 +23894,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23944,11 +23933,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index 38539a6fd3d..5d1cbc382fa 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index 25ac7079099..0ec534d15d7 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1327,6 +1327,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v02-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-07-15 08:37 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-07-15 08:37 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 81bba4beac7..8eabe232d1e 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 713bb5d10f1..5bc28c94139 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -699,6 +699,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1386,22 +1388,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1418,9 +1414,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1505,9 +1499,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1534,7 +1526,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1547,8 +1539,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -4051,27 +4043,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4159,11 +4143,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 0bf19d07db5..1ad453a39a0 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -514,13 +514,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -539,15 +537,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -557,7 +549,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -681,11 +673,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1234,7 +1223,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index cb93c3e935a..d691b317011 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23762,9 +23762,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23896,18 +23894,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23944,11 +23933,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index 38539a6fd3d..5d1cbc382fa 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index 25ac7079099..0ec534d15d7 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1327,6 +1327,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v02-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-07-15 08:37 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-07-15 08:37 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 81bba4beac7..8eabe232d1e 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 713bb5d10f1..5bc28c94139 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -699,6 +699,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1386,22 +1388,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1418,9 +1414,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1505,9 +1499,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1534,7 +1526,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1547,8 +1539,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -4051,27 +4043,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4159,11 +4143,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 0bf19d07db5..1ad453a39a0 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -514,13 +514,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -539,15 +537,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -557,7 +549,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -681,11 +673,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1234,7 +1223,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index cb93c3e935a..d691b317011 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23762,9 +23762,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23896,18 +23894,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23944,11 +23933,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index 38539a6fd3d..5d1cbc382fa 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index 25ac7079099..0ec534d15d7 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1327,6 +1327,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v02-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-07-15 08:37 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-07-15 08:37 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 81bba4beac7..8eabe232d1e 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 713bb5d10f1..5bc28c94139 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -699,6 +699,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1386,22 +1388,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1418,9 +1414,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1505,9 +1499,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1534,7 +1526,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1547,8 +1539,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -4051,27 +4043,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4159,11 +4143,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 0bf19d07db5..1ad453a39a0 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -514,13 +514,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -539,15 +537,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -557,7 +549,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -681,11 +673,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1234,7 +1223,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index cb93c3e935a..d691b317011 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23762,9 +23762,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23896,18 +23894,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23944,11 +23933,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index 38539a6fd3d..5d1cbc382fa 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index 25ac7079099..0ec534d15d7 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1327,6 +1327,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v02-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-07-15 08:37 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-07-15 08:37 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 81bba4beac7..8eabe232d1e 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 713bb5d10f1..5bc28c94139 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -699,6 +699,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1386,22 +1388,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1418,9 +1414,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1505,9 +1499,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1534,7 +1526,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1547,8 +1539,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -4051,27 +4043,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4159,11 +4143,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 0bf19d07db5..1ad453a39a0 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -514,13 +514,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -539,15 +537,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -557,7 +549,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -681,11 +673,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1234,7 +1223,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index cb93c3e935a..d691b317011 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23762,9 +23762,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23896,18 +23894,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23944,11 +23933,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index 38539a6fd3d..5d1cbc382fa 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index 25ac7079099..0ec534d15d7 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1327,6 +1327,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v02-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-07-15 08:37 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-07-15 08:37 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 81bba4beac7..8eabe232d1e 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 713bb5d10f1..5bc28c94139 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -699,6 +699,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1386,22 +1388,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1418,9 +1414,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1505,9 +1499,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1534,7 +1526,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1547,8 +1539,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -4051,27 +4043,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4159,11 +4143,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 0bf19d07db5..1ad453a39a0 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -514,13 +514,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -539,15 +537,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -557,7 +549,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -681,11 +673,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1234,7 +1223,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index cb93c3e935a..d691b317011 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23762,9 +23762,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23896,18 +23894,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23944,11 +23933,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index 38539a6fd3d..5d1cbc382fa 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index 25ac7079099..0ec534d15d7 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1327,6 +1327,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v02-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-07-15 08:37 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-07-15 08:37 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 81bba4beac7..8eabe232d1e 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 713bb5d10f1..5bc28c94139 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -699,6 +699,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1386,22 +1388,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1418,9 +1414,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1505,9 +1499,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1534,7 +1526,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1547,8 +1539,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -4051,27 +4043,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4159,11 +4143,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 0bf19d07db5..1ad453a39a0 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -514,13 +514,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -539,15 +537,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -557,7 +549,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -681,11 +673,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1234,7 +1223,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index cb93c3e935a..d691b317011 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23762,9 +23762,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23896,18 +23894,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23944,11 +23933,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index 38539a6fd3d..5d1cbc382fa 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index 25ac7079099..0ec534d15d7 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1327,6 +1327,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v02-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-07-15 08:37 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-07-15 08:37 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 81bba4beac7..8eabe232d1e 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 713bb5d10f1..5bc28c94139 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -699,6 +699,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1386,22 +1388,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1418,9 +1414,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1505,9 +1499,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1534,7 +1526,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1547,8 +1539,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -4051,27 +4043,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4159,11 +4143,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 0bf19d07db5..1ad453a39a0 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -514,13 +514,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -539,15 +537,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -557,7 +549,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -681,11 +673,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1234,7 +1223,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index cb93c3e935a..d691b317011 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23762,9 +23762,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23896,18 +23894,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23944,11 +23933,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index 38539a6fd3d..5d1cbc382fa 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index 25ac7079099..0ec534d15d7 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1327,6 +1327,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v02-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-07-15 08:37 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-07-15 08:37 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 81bba4beac7..8eabe232d1e 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 713bb5d10f1..5bc28c94139 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -699,6 +699,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1386,22 +1388,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1418,9 +1414,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1505,9 +1499,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1534,7 +1526,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1547,8 +1539,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -4051,27 +4043,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4159,11 +4143,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 0bf19d07db5..1ad453a39a0 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -514,13 +514,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -539,15 +537,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -557,7 +549,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -681,11 +673,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1234,7 +1223,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index cb93c3e935a..d691b317011 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23762,9 +23762,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23896,18 +23894,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23944,11 +23933,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index 38539a6fd3d..5d1cbc382fa 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index 25ac7079099..0ec534d15d7 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1327,6 +1327,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v02-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-07-15 08:37 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-07-15 08:37 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 81bba4beac7..8eabe232d1e 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 713bb5d10f1..5bc28c94139 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -699,6 +699,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1386,22 +1388,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1418,9 +1414,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1505,9 +1499,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1534,7 +1526,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1547,8 +1539,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -4051,27 +4043,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4159,11 +4143,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 0bf19d07db5..1ad453a39a0 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -514,13 +514,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -539,15 +537,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -557,7 +549,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -681,11 +673,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1234,7 +1223,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index cb93c3e935a..d691b317011 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23762,9 +23762,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23896,18 +23894,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23944,11 +23933,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index 38539a6fd3d..5d1cbc382fa 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index 25ac7079099..0ec534d15d7 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1327,6 +1327,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v02-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-07-15 08:37 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-07-15 08:37 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 81bba4beac7..8eabe232d1e 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 713bb5d10f1..5bc28c94139 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -699,6 +699,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1386,22 +1388,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1418,9 +1414,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1505,9 +1499,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1534,7 +1526,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1547,8 +1539,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -4051,27 +4043,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4159,11 +4143,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 0bf19d07db5..1ad453a39a0 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -514,13 +514,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -539,15 +537,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -557,7 +549,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -681,11 +673,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1234,7 +1223,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index cb93c3e935a..d691b317011 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23762,9 +23762,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23896,18 +23894,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23944,11 +23933,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index 38539a6fd3d..5d1cbc382fa 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index 25ac7079099..0ec534d15d7 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1327,6 +1327,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v02-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-07-15 08:37 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-07-15 08:37 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 81bba4beac7..8eabe232d1e 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 713bb5d10f1..5bc28c94139 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -699,6 +699,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1386,22 +1388,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1418,9 +1414,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1505,9 +1499,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1534,7 +1526,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1547,8 +1539,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -4051,27 +4043,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4159,11 +4143,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 0bf19d07db5..1ad453a39a0 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -514,13 +514,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -539,15 +537,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -557,7 +549,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -681,11 +673,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1234,7 +1223,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index cb93c3e935a..d691b317011 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23762,9 +23762,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23896,18 +23894,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23944,11 +23933,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index 38539a6fd3d..5d1cbc382fa 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index 25ac7079099..0ec534d15d7 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1327,6 +1327,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v02-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-07-15 08:37 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-07-15 08:37 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 81bba4beac7..8eabe232d1e 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 713bb5d10f1..5bc28c94139 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -699,6 +699,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1386,22 +1388,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1418,9 +1414,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1505,9 +1499,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1534,7 +1526,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1547,8 +1539,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -4051,27 +4043,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4159,11 +4143,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 0bf19d07db5..1ad453a39a0 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -514,13 +514,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -539,15 +537,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -557,7 +549,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -681,11 +673,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1234,7 +1223,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index cb93c3e935a..d691b317011 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23762,9 +23762,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23896,18 +23894,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23944,11 +23933,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index 38539a6fd3d..5d1cbc382fa 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index 25ac7079099..0ec534d15d7 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1327,6 +1327,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v02-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-07-15 08:37 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-07-15 08:37 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 81bba4beac7..8eabe232d1e 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 713bb5d10f1..5bc28c94139 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -699,6 +699,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1386,22 +1388,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1418,9 +1414,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1505,9 +1499,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1534,7 +1526,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1547,8 +1539,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -4051,27 +4043,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4159,11 +4143,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 0bf19d07db5..1ad453a39a0 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -514,13 +514,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -539,15 +537,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -557,7 +549,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -681,11 +673,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1234,7 +1223,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index cb93c3e935a..d691b317011 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23762,9 +23762,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23896,18 +23894,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23944,11 +23933,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index 38539a6fd3d..5d1cbc382fa 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index 25ac7079099..0ec534d15d7 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1327,6 +1327,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v02-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-07-15 08:37 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-07-15 08:37 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 81bba4beac7..8eabe232d1e 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 713bb5d10f1..5bc28c94139 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -699,6 +699,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1386,22 +1388,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1418,9 +1414,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1505,9 +1499,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1534,7 +1526,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1547,8 +1539,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -4051,27 +4043,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4159,11 +4143,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 0bf19d07db5..1ad453a39a0 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -514,13 +514,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -539,15 +537,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -557,7 +549,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -681,11 +673,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1234,7 +1223,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index cb93c3e935a..d691b317011 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23762,9 +23762,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23896,18 +23894,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23944,11 +23933,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index 38539a6fd3d..5d1cbc382fa 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index 25ac7079099..0ec534d15d7 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1327,6 +1327,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v02-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-07-15 08:37 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-07-15 08:37 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 81bba4beac7..8eabe232d1e 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 713bb5d10f1..5bc28c94139 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -699,6 +699,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1386,22 +1388,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1418,9 +1414,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1505,9 +1499,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1534,7 +1526,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1547,8 +1539,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -4051,27 +4043,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4159,11 +4143,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 0bf19d07db5..1ad453a39a0 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -514,13 +514,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -539,15 +537,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -557,7 +549,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -681,11 +673,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1234,7 +1223,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index cb93c3e935a..d691b317011 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23762,9 +23762,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23896,18 +23894,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23944,11 +23933,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index 38539a6fd3d..5d1cbc382fa 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index 25ac7079099..0ec534d15d7 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1327,6 +1327,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v02-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-07-15 08:37 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-07-15 08:37 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 81bba4beac7..8eabe232d1e 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 713bb5d10f1..5bc28c94139 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -699,6 +699,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1386,22 +1388,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1418,9 +1414,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1505,9 +1499,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1534,7 +1526,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1547,8 +1539,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -4051,27 +4043,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4159,11 +4143,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 0bf19d07db5..1ad453a39a0 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -514,13 +514,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -539,15 +537,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -557,7 +549,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -681,11 +673,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1234,7 +1223,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index cb93c3e935a..d691b317011 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23762,9 +23762,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23896,18 +23894,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23944,11 +23933,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index 38539a6fd3d..5d1cbc382fa 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index 25ac7079099..0ec534d15d7 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1327,6 +1327,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v02-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-07-15 08:37 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-07-15 08:37 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 81bba4beac7..8eabe232d1e 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 713bb5d10f1..5bc28c94139 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -699,6 +699,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1386,22 +1388,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1418,9 +1414,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1505,9 +1499,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1534,7 +1526,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1547,8 +1539,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -4051,27 +4043,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4159,11 +4143,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 0bf19d07db5..1ad453a39a0 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -514,13 +514,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -539,15 +537,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -557,7 +549,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -681,11 +673,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1234,7 +1223,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index cb93c3e935a..d691b317011 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23762,9 +23762,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23896,18 +23894,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23944,11 +23933,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index 38539a6fd3d..5d1cbc382fa 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index 25ac7079099..0ec534d15d7 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1327,6 +1327,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v02-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-07-15 08:37 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-07-15 08:37 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 81bba4beac7..8eabe232d1e 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 713bb5d10f1..5bc28c94139 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -699,6 +699,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1386,22 +1388,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1418,9 +1414,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1505,9 +1499,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1534,7 +1526,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1547,8 +1539,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -4051,27 +4043,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4159,11 +4143,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 0bf19d07db5..1ad453a39a0 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -514,13 +514,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -539,15 +537,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -557,7 +549,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -681,11 +673,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1234,7 +1223,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index cb93c3e935a..d691b317011 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23762,9 +23762,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23896,18 +23894,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23944,11 +23933,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index 38539a6fd3d..5d1cbc382fa 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index 25ac7079099..0ec534d15d7 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1327,6 +1327,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v02-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-07-15 08:37 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-07-15 08:37 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 81bba4beac7..8eabe232d1e 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 713bb5d10f1..5bc28c94139 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -699,6 +699,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1386,22 +1388,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1418,9 +1414,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1505,9 +1499,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1534,7 +1526,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1547,8 +1539,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -4051,27 +4043,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4159,11 +4143,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 0bf19d07db5..1ad453a39a0 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -514,13 +514,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -539,15 +537,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -557,7 +549,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -681,11 +673,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1234,7 +1223,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index cb93c3e935a..d691b317011 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23762,9 +23762,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23896,18 +23894,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23944,11 +23933,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index 38539a6fd3d..5d1cbc382fa 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index 25ac7079099..0ec534d15d7 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1327,6 +1327,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v02-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-07-15 08:37 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-07-15 08:37 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 81bba4beac7..8eabe232d1e 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 713bb5d10f1..5bc28c94139 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -699,6 +699,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1386,22 +1388,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1418,9 +1414,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1505,9 +1499,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1534,7 +1526,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1547,8 +1539,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -4051,27 +4043,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4159,11 +4143,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 0bf19d07db5..1ad453a39a0 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -514,13 +514,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -539,15 +537,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -557,7 +549,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -681,11 +673,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1234,7 +1223,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index cb93c3e935a..d691b317011 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23762,9 +23762,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23896,18 +23894,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23944,11 +23933,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index 38539a6fd3d..5d1cbc382fa 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index 25ac7079099..0ec534d15d7 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1327,6 +1327,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v02-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-07-15 08:37 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-07-15 08:37 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 81bba4beac7..8eabe232d1e 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 713bb5d10f1..5bc28c94139 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -699,6 +699,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1386,22 +1388,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1418,9 +1414,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1505,9 +1499,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1534,7 +1526,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1547,8 +1539,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -4051,27 +4043,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4159,11 +4143,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 0bf19d07db5..1ad453a39a0 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -514,13 +514,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -539,15 +537,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -557,7 +549,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -681,11 +673,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1234,7 +1223,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index cb93c3e935a..d691b317011 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23762,9 +23762,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23896,18 +23894,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23944,11 +23933,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index 38539a6fd3d..5d1cbc382fa 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index 25ac7079099..0ec534d15d7 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1327,6 +1327,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v02-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-07-15 08:37 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-07-15 08:37 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 81bba4beac7..8eabe232d1e 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 713bb5d10f1..5bc28c94139 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -699,6 +699,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1386,22 +1388,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1418,9 +1414,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1505,9 +1499,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1534,7 +1526,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1547,8 +1539,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -4051,27 +4043,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4159,11 +4143,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 0bf19d07db5..1ad453a39a0 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -514,13 +514,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -539,15 +537,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -557,7 +549,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -681,11 +673,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1234,7 +1223,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index cb93c3e935a..d691b317011 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23762,9 +23762,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23896,18 +23894,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23944,11 +23933,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index 38539a6fd3d..5d1cbc382fa 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index 25ac7079099..0ec534d15d7 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1327,6 +1327,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v02-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-07-15 08:37 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-07-15 08:37 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 81bba4beac7..8eabe232d1e 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 713bb5d10f1..5bc28c94139 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -699,6 +699,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1386,22 +1388,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1418,9 +1414,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1505,9 +1499,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1534,7 +1526,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1547,8 +1539,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -4051,27 +4043,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4159,11 +4143,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 0bf19d07db5..1ad453a39a0 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -514,13 +514,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -539,15 +537,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -557,7 +549,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -681,11 +673,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1234,7 +1223,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index cb93c3e935a..d691b317011 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23762,9 +23762,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23896,18 +23894,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23944,11 +23933,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index 38539a6fd3d..5d1cbc382fa 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index 25ac7079099..0ec534d15d7 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1327,6 +1327,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v02-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-07-15 08:37 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-07-15 08:37 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 81bba4beac7..8eabe232d1e 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 713bb5d10f1..5bc28c94139 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -699,6 +699,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1386,22 +1388,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1418,9 +1414,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1505,9 +1499,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1534,7 +1526,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1547,8 +1539,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -4051,27 +4043,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4159,11 +4143,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 0bf19d07db5..1ad453a39a0 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -514,13 +514,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -539,15 +537,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -557,7 +549,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -681,11 +673,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1234,7 +1223,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index cb93c3e935a..d691b317011 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23762,9 +23762,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23896,18 +23894,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23944,11 +23933,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index 38539a6fd3d..5d1cbc382fa 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index 25ac7079099..0ec534d15d7 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1327,6 +1327,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v02-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-07-15 08:37 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-07-15 08:37 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 81bba4beac7..8eabe232d1e 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 713bb5d10f1..5bc28c94139 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -699,6 +699,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1386,22 +1388,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1418,9 +1414,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1505,9 +1499,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1534,7 +1526,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1547,8 +1539,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -4051,27 +4043,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4159,11 +4143,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 0bf19d07db5..1ad453a39a0 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -514,13 +514,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -539,15 +537,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -557,7 +549,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -681,11 +673,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1234,7 +1223,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index cb93c3e935a..d691b317011 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23762,9 +23762,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23896,18 +23894,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23944,11 +23933,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index 38539a6fd3d..5d1cbc382fa 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index 25ac7079099..0ec534d15d7 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1327,6 +1327,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v02-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-07-15 08:37 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-07-15 08:37 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 81bba4beac7..8eabe232d1e 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 713bb5d10f1..5bc28c94139 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -699,6 +699,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1386,22 +1388,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1418,9 +1414,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1505,9 +1499,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1534,7 +1526,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1547,8 +1539,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -4051,27 +4043,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4159,11 +4143,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 0bf19d07db5..1ad453a39a0 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -514,13 +514,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -539,15 +537,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -557,7 +549,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -681,11 +673,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1234,7 +1223,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index cb93c3e935a..d691b317011 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23762,9 +23762,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23896,18 +23894,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23944,11 +23933,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index 38539a6fd3d..5d1cbc382fa 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index 25ac7079099..0ec534d15d7 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1327,6 +1327,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v02-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-07-15 08:37 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-07-15 08:37 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 81bba4beac7..8eabe232d1e 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 713bb5d10f1..5bc28c94139 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -699,6 +699,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1386,22 +1388,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1418,9 +1414,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1505,9 +1499,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1534,7 +1526,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1547,8 +1539,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -4051,27 +4043,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4159,11 +4143,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 0bf19d07db5..1ad453a39a0 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -514,13 +514,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -539,15 +537,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -557,7 +549,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -681,11 +673,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1234,7 +1223,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index cb93c3e935a..d691b317011 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23762,9 +23762,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23896,18 +23894,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23944,11 +23933,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index 38539a6fd3d..5d1cbc382fa 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index 25ac7079099..0ec534d15d7 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1327,6 +1327,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v02-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-07-15 08:37 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-07-15 08:37 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 81bba4beac7..8eabe232d1e 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 713bb5d10f1..5bc28c94139 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -699,6 +699,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1386,22 +1388,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1418,9 +1414,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1505,9 +1499,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1534,7 +1526,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1547,8 +1539,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -4051,27 +4043,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4159,11 +4143,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 0bf19d07db5..1ad453a39a0 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -514,13 +514,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -539,15 +537,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -557,7 +549,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -681,11 +673,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1234,7 +1223,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index cb93c3e935a..d691b317011 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23762,9 +23762,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23896,18 +23894,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23944,11 +23933,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index 38539a6fd3d..5d1cbc382fa 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index 25ac7079099..0ec534d15d7 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1327,6 +1327,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v02-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-07-15 08:37 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-07-15 08:37 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 81bba4beac7..8eabe232d1e 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 713bb5d10f1..5bc28c94139 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -699,6 +699,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1386,22 +1388,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1418,9 +1414,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1505,9 +1499,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1534,7 +1526,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1547,8 +1539,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -4051,27 +4043,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4159,11 +4143,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 0bf19d07db5..1ad453a39a0 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -514,13 +514,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -539,15 +537,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -557,7 +549,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -681,11 +673,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1234,7 +1223,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index cb93c3e935a..d691b317011 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23762,9 +23762,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23896,18 +23894,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23944,11 +23933,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index 38539a6fd3d..5d1cbc382fa 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index 25ac7079099..0ec534d15d7 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1327,6 +1327,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v02-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
* [PATCH 5/8] Simplify the way restrictions are imposed on index functions. @ 2026-07-15 08:37 Antonin Houska <[email protected]> 0 siblings, 0 replies; 108+ messages in thread From: Antonin Houska @ 2026-07-15 08:37 UTC (permalink / raw) Whenever we expect possible execution of index functions, we need to make sure that they execute with the appropriate privileges. Also, the core should not see (and use) values of GUC parameters introduced by the index functions. This patch introduces functions enable_index_build_security() and disable_index_build_security() which make the security measures less verbose. It's needed for the upcoming enhancements of REPACK (CONCURRENTLY), but looks like useful refactoring anyway. --- src/backend/access/brin/brin.c | 32 ++++---------- src/backend/catalog/index.c | 72 ++++++++++++++++++-------------- src/backend/commands/analyze.c | 21 +++------- src/backend/commands/indexcmds.c | 49 +++++++--------------- src/backend/commands/repack.c | 24 +++-------- src/backend/commands/tablecmds.c | 24 +++-------- src/backend/commands/vacuum.c | 23 +++------- src/include/catalog/index.h | 10 +++++ src/tools/pgindent/typedefs.list | 1 + 9 files changed, 95 insertions(+), 161 deletions(-) diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index bdb30752e09..2359bffa518 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1391,10 +1391,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) Oid heapoid; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; double numSummarized = 0; + IndexBuildSecurity ibsec; if (RecoveryInProgress()) ereport(ERROR, @@ -1420,27 +1418,12 @@ brin_summarize_range(PG_FUNCTION_ARGS) heapRel = table_open(heapoid, ShareUpdateExclusiveLock); /* - * Autovacuum calls us. For its benefit, switch to the table owner's - * userid, so that any index functions are run as that user. Also - * lock down security-restricted operations and arrange to make GUC - * variable changes local to this command. This is harmless, albeit - * unnecessary, when called from SQL, because we fail shortly if the - * user does not own the index. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); } else - { heapRel = NULL; - /* Set these just to suppress "uninitialized variable" warnings */ - save_userid = InvalidOid; - save_sec_context = -1; - save_nestlevel = -1; - } indexRel = index_open(indexoid, ShareUpdateExclusiveLock); @@ -1453,7 +1436,8 @@ brin_summarize_range(PG_FUNCTION_ARGS) RelationGetRelationName(indexRel)))); /* User must own the index (comparable to privileges needed for VACUUM) */ - if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid)) + if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, + ibsec.userid)) aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX, RelationGetRelationName(indexRel)); @@ -1477,11 +1461,9 @@ brin_summarize_range(PG_FUNCTION_ARGS) errmsg("index \"%s\" is not valid", RelationGetRelationName(indexRel)))); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); index_close(indexRel, ShareUpdateExclusiveLock); table_close(heapRel, ShareUpdateExclusiveLock); diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 81bba4beac7..8eabe232d1e 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1504,11 +1504,9 @@ index_concurrently_build(Oid heapRelationId, Oid indexRelationId) { Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation indexRelation; IndexInfo *indexInfo; + IndexBuildSecurity ibsec; /* This had better make sure that a snapshot is active */ Assert(ActiveSnapshotSet()); @@ -1517,15 +1515,9 @@ index_concurrently_build(Oid heapRelationId, heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); indexRelation = index_open(indexRelationId, RowExclusiveLock); @@ -1542,11 +1534,8 @@ index_concurrently_build(Oid heapRelationId, /* Now build the index */ index_build(heapRel, indexRelation, indexInfo, false, true, true); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close both the relations, but keep the locks */ table_close(heapRel, NoLock); @@ -3375,9 +3364,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) IndexInfo *indexInfo; IndexVacuumInfo ivinfo; ValidateIndexState state; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; { const int progress_index[] = { @@ -3399,15 +3386,9 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) heapRelation = table_open(heapId, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRelation->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRelation->rd_rel->relowner, &ibsec); indexRelation = index_open(indexId, RowExclusiveLock); @@ -3486,11 +3467,8 @@ validate_index(Oid heapId, Oid indexId, Snapshot snapshot) "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples", state.htups, state.itups, state.tups_inserted); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Close rels, but keep locks */ index_close(indexRelation, NoLock); @@ -4115,6 +4093,36 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, return result; } +/* + * Before building an index, witch to the table owner's userid, so that any + * index functions are run as that user. Also lock down security-restricted + * operations and arrange to make GUC variable changes local to this command. + * + * Information needed later by disable_index_build_security() is stored in + * *sec. + */ +void +enable_index_build_security(Oid userid, IndexBuildSecurity *sec) +{ + GetUserIdAndSecContext(&sec->userid, &sec->sec_context); + SetUserIdAndSecContext(userid, + sec->sec_context | SECURITY_RESTRICTED_OPERATION); + sec->nestlevel = NewGUCNestLevel(); + RestrictSearchPath(); +} + +/* + * Undo what enable_index_build_security() did. + */ +void +disable_index_build_security(IndexBuildSecurity *sec) +{ + /* Roll back any GUC changes executed by index functions */ + AtEOXact_GUC(false, sec->nestlevel); + + /* Restore userid and security context */ + SetUserIdAndSecContext(sec->userid, sec->sec_context); +} /* ---------------------------------------------------------------- * System index reindexing support diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index f66e80b757c..dc2ad77ef9a 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -328,14 +328,12 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, PGRUsage ru0; TimestampTz starttime = 0; MemoryContext caller_context; - Oid save_userid; - int save_sec_context; - int save_nestlevel; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; BufferUsage bufferusage; PgStat_Counter startreadtime = 0; PgStat_Counter startwritetime = 0; + IndexBuildSecurity ibsec; verbose = (params->options & VACOPT_VERBOSE) != 0; instrument = (verbose || (AmAutoVacuumWorkerProcess() && @@ -361,15 +359,9 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, caller_context = MemoryContextSwitchTo(anl_context); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(onerel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(onerel->rd_rel->relowner, &ibsec); /* * When verbose or autovacuum logging is used, initialize a resource usage @@ -858,11 +850,8 @@ do_analyze_rel(Relation onerel, const VacuumParams *params, } } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* Restore current context and release memory */ MemoryContextSwitchTo(caller_context); diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c index 713bb5d10f1..5bc28c94139 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -699,6 +699,8 @@ DefineIndex(ParseState *pstate, * Switch to the table owner's userid, so that any index functions are run * as that user. Also lock down security-restricted operations. We * already arranged to make GUC variable changes local to this command. + * + * XXX Use enable_index_build_security()? */ GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); SetUserIdAndSecContext(rel->rd_rel->relowner, @@ -1386,22 +1388,16 @@ DefineIndex(ParseState *pstate, { Oid childRelid = part_oids[i]; Relation childrel; - Oid child_save_userid; - int child_save_sec_context; - int child_save_nestlevel; List *childidxs; ListCell *cell; AttrMap *attmap; bool found = false; + IndexBuildSecurity child_ibsec; childrel = table_open(childRelid, lockmode); - GetUserIdAndSecContext(&child_save_userid, - &child_save_sec_context); - SetUserIdAndSecContext(childrel->rd_rel->relowner, - child_save_sec_context | SECURITY_RESTRICTED_OPERATION); - child_save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(childrel->rd_rel->relowner, + &child_ibsec); /* * Don't try to create indexes on foreign tables, though. Skip @@ -1418,9 +1414,7 @@ DefineIndex(ParseState *pstate, errdetail("Table \"%s\" contains partitions that are foreign tables.", RelationGetRelationName(rel)))); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, lockmode); continue; } @@ -1505,9 +1499,7 @@ DefineIndex(ParseState *pstate, } list_free(childidxs); - AtEOXact_GUC(false, child_save_nestlevel); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + disable_index_build_security(&child_ibsec); table_close(childrel, NoLock); /* @@ -1534,7 +1526,7 @@ DefineIndex(ParseState *pstate, * Recurse as the starting user ID. Callee will use that * for permission checks, then switch again. */ - Assert(GetUserId() == child_save_userid); + Assert(GetUserId() == child_ibsec.userid); SetUserIdAndSecContext(root_save_userid, root_save_sec_context); childAddr = @@ -1547,8 +1539,8 @@ DefineIndex(ParseState *pstate, is_alter_table, check_rights, check_not_in_use, skip_build, quiet); - SetUserIdAndSecContext(child_save_userid, - child_save_sec_context); + SetUserIdAndSecContext(child_ibsec.userid, + child_ibsec.sec_context); /* * Check if the index just created is valid or not, as it @@ -4051,27 +4043,19 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein Oid newIndexId; Relation indexRel; Relation heapRel; - Oid save_userid; - int save_sec_context; - int save_nestlevel; Relation newIndexRel; LockRelId *lockrelid; Oid tablespaceid; + IndexBuildSecurity ibsec; indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); heapRel = table_open(indexRel->rd_index->indrelid, ShareUpdateExclusiveLock); /* - * Switch to the table owner's userid, so that any index functions are - * run as that user. Also lock down security-restricted operations - * and arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(heapRel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(heapRel->rd_rel->relowner, &ibsec); /* determine safety of this index for set_indexsafe_procflags */ idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && @@ -4159,11 +4143,8 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein index_close(indexRel, NoLock); index_close(newIndexRel, NoLock); - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); table_close(heapRel, NoLock); diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 0bf19d07db5..1ad453a39a0 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -514,13 +514,11 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid tableOid = RelationGetRelid(OldHeap); Relation index; LOCKMODE lmode; - Oid save_userid; - int save_sec_context; - int save_nestlevel; bool verbose = ((params->options & CLUOPT_VERBOSE) != 0); bool recheck = ((params->options & CLUOPT_RECHECK) != 0); bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0); Oid ident_idx = InvalidOid; + IndexBuildSecurity ibsec; /* Determine the lock mode to use. */ lmode = RepackLockLevel(concurrent); @@ -539,15 +537,9 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, pgstat_progress_update_param(PROGRESS_REPACK_COMMAND, cmd); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(OldHeap->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(OldHeap->rd_rel->relowner, &ibsec); /* * Recheck that the relation is still what it was when we started. @@ -557,7 +549,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, * not-previously-clustered index. */ if (recheck && - !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid, + !cluster_rel_recheck(cmd, OldHeap, indexOid, GetUserId(), lmode, params->options)) goto out; @@ -681,11 +673,8 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, rebuild_relation(OldHeap, index, verbose, ident_idx); out: - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); pgstat_progress_end_command(); } @@ -1234,7 +1223,6 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose, } } - /* * Create the transient table that will be filled with new data during * CLUSTER, ALTER TABLE, and similar operations. The transient table diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index cb93c3e935a..d691b317011 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -23762,9 +23762,7 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, Oid defaultPartOid; Oid existingRelid; Oid ownerId = InvalidOid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; + IndexBuildSecurity ibsec; /* * Check ownership of merged partitions - partitions with different owners @@ -23896,18 +23894,9 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId); /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also, lockdown security-restricted operations and - * arrange to make GUC variable changes local to this command. - * - * Need to do it after determining the namespace in the - * createPartitionTable() call. + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(ownerId, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(ownerId, &ibsec); /* Copy data from merged partitions to the new partition. */ MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel); @@ -23944,11 +23933,8 @@ ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel, /* Keep the lock until commit. */ table_close(newPartRel, NoLock); - /* Roll back any GUC changes executed by index functions. */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore the userid and security context. */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); } /* diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index 38539a6fd3d..5d1cbc382fa 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -34,6 +34,7 @@ #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" +#include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_database.h" #include "catalog/pg_inherits.h" @@ -2017,10 +2018,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, LockRelId lockrelid; Oid priv_relid; Oid toast_relid; - Oid save_userid; - int save_sec_context; - int save_nestlevel; VacuumParams toast_vacuum_params; + IndexBuildSecurity ibsec; /* * This function scribbles on the parameters, so make a copy early to @@ -2270,16 +2269,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, toast_relid = InvalidOid; /* - * Switch to the table owner's userid, so that any index functions are run - * as that user. Also lock down security-restricted operations and - * arrange to make GUC variable changes local to this command. (This is - * unnecessary, but harmless, for lazy VACUUM.) + * Prevent index functions from doing what they are not supposed to. */ - GetUserIdAndSecContext(&save_userid, &save_sec_context); - SetUserIdAndSecContext(rel->rd_rel->relowner, - save_sec_context | SECURITY_RESTRICTED_OPERATION); - save_nestlevel = NewGUCNestLevel(); - RestrictSearchPath(); + enable_index_build_security(rel->rd_rel->relowner, &ibsec); /* * If PROCESS_MAIN is set (the default), it's time to vacuum the main @@ -2310,11 +2302,8 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, table_relation_vacuum(rel, ¶ms, bstrategy); } - /* Roll back any GUC changes executed by index functions */ - AtEOXact_GUC(false, save_nestlevel); - - /* Restore userid and security context */ - SetUserIdAndSecContext(save_userid, save_sec_context); + /* Relax the restrictions imposed above. */ + disable_index_build_security(&ibsec); /* all done with this class, but hold lock until commit */ if (rel) diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 9aee8226347..dd9ae8119e5 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -172,6 +172,16 @@ extern void reindex_index(const ReindexStmt *stmt, Oid indexId, extern bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params); +typedef struct IndexBuildSecurity +{ + Oid userid; + int sec_context; + int nestlevel; +} IndexBuildSecurity; + +extern void enable_index_build_security(Oid userid, IndexBuildSecurity *sec); +extern void disable_index_build_security(IndexBuildSecurity *sec); + extern bool ReindexIsProcessingHeap(Oid heapOid); extern bool ReindexIsProcessingIndex(Oid indexOid); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index 25ac7079099..0ec534d15d7 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1327,6 +1327,7 @@ IndexAttachInfo IndexAttrBitmapKind IndexBuildCallback IndexBuildResult +IndexBuildSecurity IndexBulkDeleteCallback IndexBulkDeleteResult IndexClause -- 2.52.0 --=-=-= Content-Type: text/x-diff Content-Disposition: attachment; filename=v02-0006-Use-separate-transactions-for-catalog-changes.patch ^ permalink raw reply [nested|flat] 108+ messages in thread
end of thread, other threads:[~2026-07-15 08:37 UTC | newest] Thread overview: 108+ messages (download: mbox mbox.gz follow: Atom feed) -- links below jump to the message on this page -- 2025-11-04 13:52 [PATCH v7 3/3] handle relation statistics correctly during rewrites Bertrand Drouvot <[email protected]> 2026-06-16 11:54 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-06-16 11:54 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-06-16 11:54 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-06-16 11:54 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-06-16 11:54 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-06-16 11:54 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-06-16 11:54 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-06-16 11:54 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-06-16 11:54 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-06-16 11:54 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-06-16 11:54 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-06-16 11:54 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-06-16 11:54 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-06-16 11:54 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-06-16 11:54 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-06-16 11:54 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-06-16 11:54 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-06-16 11:54 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-06-16 11:54 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-06-16 11:54 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-06-16 11:54 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-06-16 11:54 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-06-16 11:54 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-06-16 11:54 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-06-16 11:54 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-06-16 11:54 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-06-16 11:54 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-06-16 11:54 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-06-16 11:54 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-06-16 11:54 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-06-16 11:54 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-06-16 11:54 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-06-16 11:54 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-06-16 11:54 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-06-16 11:54 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-06-16 11:54 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-06-16 11:54 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-06-16 11:54 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-06-16 11:54 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-06-16 11:54 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-06-16 11:54 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-06-16 11:54 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-06-16 11:54 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-06-16 11:54 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-06-16 11:54 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-06-16 11:54 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-06-16 11:54 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-06-16 11:54 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-06-16 11:54 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-06-16 11:54 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-06-16 11:54 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-06-16 11:54 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-06-16 11:54 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-06-16 11:54 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-07-15 08:37 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-07-15 08:37 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-07-15 08:37 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-07-15 08:37 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-07-15 08:37 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-07-15 08:37 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-07-15 08:37 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-07-15 08:37 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-07-15 08:37 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-07-15 08:37 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-07-15 08:37 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-07-15 08:37 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-07-15 08:37 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-07-15 08:37 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-07-15 08:37 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-07-15 08:37 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-07-15 08:37 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-07-15 08:37 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-07-15 08:37 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-07-15 08:37 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-07-15 08:37 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-07-15 08:37 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-07-15 08:37 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-07-15 08:37 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-07-15 08:37 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-07-15 08:37 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-07-15 08:37 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-07-15 08:37 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-07-15 08:37 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-07-15 08:37 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-07-15 08:37 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-07-15 08:37 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-07-15 08:37 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-07-15 08:37 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-07-15 08:37 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-07-15 08:37 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-07-15 08:37 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-07-15 08:37 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-07-15 08:37 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-07-15 08:37 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-07-15 08:37 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-07-15 08:37 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-07-15 08:37 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-07-15 08:37 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-07-15 08:37 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-07-15 08:37 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-07-15 08:37 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-07-15 08:37 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-07-15 08:37 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-07-15 08:37 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-07-15 08:37 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-07-15 08:37 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]> 2026-07-15 08:37 [PATCH 5/8] Simplify the way restrictions are imposed on index functions. Antonin Houska <[email protected]>
This inbox is served by agora; see mirroring instructions for how to clone and mirror all data and code used for this inbox