From 90e76f42d022c2c4d758640cabb85c87a5760cf6 Mon Sep 17 00:00:00 2001
From: zibuyu <zibuyu423@gmail.com>
Date: Thu, 3 Dec 2026 22:28:44 +0800
Subject: [PATCH] pg_dumpall: Restore circular role administration grants

A role can acquire an independent source of ADMIN OPTION, grant it back to an earlier grantor, and later lose that independent source. The surviving grants may then be impossible to replay in any order.

Order role grants by their incoming ADMIN dependencies. Restore cycles with temporary bootstrap grants in an atomic SQL procedure, removing each temporary membership or ADMIN option before returning. Cover the grantors and all membership options in a dump/restore round trip.
---
 src/bin/pg_dump/pg_dumpall.c                 | 158 ++++++++++++++++---
 src/bin/pg_dump/t/003_pg_dump_with_server.pl |  48 ++++++
 2 files changed, 180 insertions(+), 26 deletions(-)

diff --git a/src/bin/pg_dump/pg_dumpall.c b/src/bin/pg_dump/pg_dumpall.c
index aee76bb476..c245c82fed 100644
--- a/src/bin/pg_dump/pg_dumpall.c
+++ b/src/bin/pg_dump/pg_dumpall.c
@@ -40,6 +40,10 @@ typedef struct
 	uint32		status;
 	uint32		hashval;
 	char	   *rolename;
+	int			pending_admin;	/* incoming ADMIN grants still to dump */
+	bool		has_admin;
+	bool		bootstrap_grant;
+	bool		bootstrap_admin;
 } RoleNameEntry;
 
 #define SH_PREFIX	rolename
@@ -999,6 +1003,50 @@ dumpRoles(PGconn *conn)
 }
 
 
+/*
+ * A cycle of ADMIN grants cannot in general be replayed in any order.
+ * Temporarily give the remaining grantors an independent source of ADMIN
+ * OPTION, mirroring how the cycle could have been created in the first place.
+ * Record how to put each bootstrap grant back as it was.
+ */
+static void
+prepareCircularRoleGrants(PGresult *res, int start, int end, const bool *done,
+						  rolename_hash *ht, const char *role, int i_grantor,
+						  PQExpBuffer grants, PQExpBuffer revokes)
+{
+	for (int i = start; i < end; i++)
+	{
+		char	   *grantor;
+		RoleNameEntry *entry;
+
+		if (done[i - start])
+			continue;
+
+		grantor = PQgetvalue(res, i, i_grantor);
+		entry = rolename_lookup(ht, grantor);
+		if (entry == NULL || (!entry->has_admin && entry->pending_admin == 0))
+			pg_fatal("could not find a legal dump ordering for memberships in role \"%s\"", role);
+
+		if (entry->bootstrap_admin)
+			continue;
+
+		appendPQExpBuffer(grants, "GRANT %s", fmtId(role));
+		appendPQExpBuffer(grants, " TO %s WITH ADMIN OPTION", fmtId(grantor));
+		if (!entry->bootstrap_grant)
+			appendPQExpBufferStr(grants, ", INHERIT FALSE, SET FALSE");
+		appendPQExpBufferStr(grants, ";\n");
+
+		appendPQExpBuffer(revokes, "REVOKE %s%s",
+						  entry->bootstrap_grant ? "ADMIN OPTION FOR " : "",
+						  fmtId(role));
+		appendPQExpBuffer(revokes, " FROM %s;\n", fmtId(grantor));
+
+		entry->has_admin = true;
+		entry->bootstrap_admin = true;
+	}
+}
+
+
 /*
  * Dump role memberships.
  *
@@ -1083,10 +1131,11 @@ dumpRoleMembership(PGconn *conn)
 	 * We handle this by considering these grants role by role. For each role,
 	 * we initially consider the only allowable grantor to be the bootstrap
 	 * superuser. Every time we grant ADMIN OPTION on the role to some user,
-	 * that user also becomes an allowable grantor. We make repeated passes
-	 * over the grants for the role, each time dumping those whose grantors
-	 * are allowable and which we haven't done yet. Eventually this should let
-	 * us dump all the grants.
+	 * that user can also act as a grantor.  Wait until all incoming ADMIN
+	 * grants to a grantor have been dumped before dumping its outgoing
+	 * grants.  In an acyclic graph these passes will emit every grant; if we
+	 * stall, the remaining grants include a cycle that needs temporary
+	 * support.
 	 */
 	total = PQntuples(res);
 	while (start < total)
@@ -1097,6 +1146,8 @@ dumpRoleMembership(PGconn *conn)
 		int			remaining;
 		int			prev_remaining = 0;
 		rolename_hash *ht;
+		PQExpBuffer circular = NULL;
+		PQExpBuffer revokes = NULL;
 
 		/* If we hit a null roleid, we're done (nulls sort to the end). */
 		if (PQgetisnull(res, start, i_role))
@@ -1121,10 +1172,28 @@ dumpRoleMembership(PGconn *conn)
 		done = pg_malloc0_array(bool, remaining);
 
 		/*
-		 * We use a hashtable to track the member names that have been granted
-		 * admin option.  Usually a hashtable is overkill, but sometimes not.
+		 * Count incoming ADMIN grants for each member.  Also track the grants
+		 * already emitted while ordering the remaining ones below.
 		 */
 		ht = rolename_create(remaining, NULL);
+		for (i = start; i < end; ++i)
+		{
+			RoleNameEntry *entry;
+			bool		found;
+
+			if (PQgetisnull(res, i, i_member))
+				continue;
+			entry = rolename_insert(ht, PQgetvalue(res, i, i_member), &found);
+			if (!found)
+			{
+				entry->pending_admin = 0;
+				entry->has_admin = false;
+				entry->bootstrap_grant = false;
+				entry->bootstrap_admin = false;
+			}
+			if (*PQgetvalue(res, i, i_admin_option) == 't')
+				entry->pending_admin++;
+		}
 
 		/*
 		 * Make repeated passes over the grants for this role until all have
@@ -1132,18 +1201,13 @@ dumpRoleMembership(PGconn *conn)
 		 */
 		while (remaining > 0)
 		{
-			/*
-			 * We should make progress on every iteration, because a notional
-			 * graph whose vertices are grants and whose edges point from
-			 * grantors to members should be connected and acyclic. If we fail
-			 * to make progress, either we or the server have messed up.
-			 */
 			if (remaining == prev_remaining)
 			{
-				pg_log_error("could not find a legal dump ordering for memberships in role \"%s\"",
-							 role);
-				PQfinish(conn);
-				exit_nicely(1);
+				Assert(circular == NULL);
+				circular = createPQExpBuffer();
+				revokes = createPQExpBuffer();
+				prepareCircularRoleGrants(res, start, end, done, ht, role,
+										  i_grantor, circular, revokes);
 			}
 			prev_remaining = remaining;
 
@@ -1156,7 +1220,7 @@ dumpRoleMembership(PGconn *conn)
 				bool		dump_this_grantor = dump_grantors;
 				char	   *set_option = "true";
 				char	   *admin_option;
-				bool		found;
+				RoleNameEntry *entry;
 
 				/* If we already did this grant, don't do it again. */
 				if (done[i - start])
@@ -1201,9 +1265,13 @@ dumpRoleMembership(PGconn *conn)
 				 * OPTION.
 				 */
 				if (dump_this_grantor &&
-					atooid(grantorid) != BOOTSTRAP_SUPERUSERID &&
-					rolename_lookup(ht, grantor) == NULL)
-					continue;
+					atooid(grantorid) != BOOTSTRAP_SUPERUSERID)
+				{
+					entry = rolename_lookup(ht, grantor);
+					if (entry == NULL || !entry->has_admin ||
+						(circular == NULL && entry->pending_admin > 0))
+						continue;
+				}
 
 				/* Remember that we did this so that we don't do it again. */
 				done[i - start] = true;
@@ -1213,13 +1281,22 @@ dumpRoleMembership(PGconn *conn)
 				 * If ADMIN OPTION is being granted, remember that grants
 				 * listing this member as the grantor can now be dumped.
 				 */
+				entry = rolename_lookup(ht, member);
 				if (*admin_option == 't')
-					rolename_insert(ht, member, &found);
+				{
+					entry->has_admin = true;
+					entry->pending_admin--;
+				}
+				if (dump_this_grantor && atooid(grantorid) == BOOTSTRAP_SUPERUSERID)
+				{
+					entry->bootstrap_grant = true;
+					entry->bootstrap_admin = (*admin_option == 't');
+				}
 
 				/* Generate the actual GRANT statement. */
 				resetPQExpBuffer(optbuf);
-				fprintf(OPF, "GRANT %s", fmtId(role));
-				fprintf(OPF, " TO %s", fmtId(member));
+				printfPQExpBuffer(buf, "GRANT %s", fmtId(role));
+				appendPQExpBuffer(buf, " TO %s", fmtId(member));
 				if (*admin_option == 't')
 					appendPQExpBufferStr(optbuf, "ADMIN OPTION");
 				if (dump_grant_options)
@@ -1240,13 +1317,41 @@ dumpRoleMembership(PGconn *conn)
 					appendPQExpBufferStr(optbuf, "SET FALSE");
 				}
 				if (optbuf->data[0] != '\0')
-					fprintf(OPF, " WITH %s", optbuf->data);
+					appendPQExpBuffer(buf, " WITH %s", optbuf->data);
 				if (dump_this_grantor)
-					fprintf(OPF, " GRANTED BY %s", fmtId(grantor));
-				fprintf(OPF, ";\n");
+					appendPQExpBuffer(buf, " GRANTED BY %s", fmtId(grantor));
+				appendPQExpBufferStr(buf, ";\n");
+				if (circular)
+					appendPQExpBufferStr(circular, buf->data);
+				else
+					fputs(buf->data, OPF);
 			}
 		}
 
+		if (circular && revokes->len > 0)
+		{
+			/*
+			 * Execute the temporary grants and their cleanup as a single
+			 * statement.  A failed or interrupted restore must not expose the
+			 * intermediate privileges or commit an outer transaction.
+			 */
+			appendPQExpBufferStr(circular, revokes->data);
+			resetPQExpBuffer(buf);
+			if (disable_dollar_quoting)
+				appendStringLiteralConn(buf, circular->data, conn);
+			else
+				appendStringLiteralDQ(buf, circular->data, "grants");
+			fprintf(OPF, "CREATE PROCEDURE pg_temp.restore_role_memberships()"
+					" LANGUAGE SQL AS %s;\n", buf->data);
+			fprintf(OPF, "CALL pg_temp.restore_role_memberships();\n");
+			fprintf(OPF, "DROP PROCEDURE pg_temp.restore_role_memberships();\n");
+		}
+		else if (circular)
+			fputs(circular->data, OPF);
+
+		destroyPQExpBuffer(circular);
+		destroyPQExpBuffer(revokes);
+
 		rolename_destroy(ht);
 		pg_free(done);
 		start = end;
@@ -1254,6 +1359,7 @@ dumpRoleMembership(PGconn *conn)
 
 	PQclear(res);
 	destroyPQExpBuffer(buf);
+	destroyPQExpBuffer(optbuf);
 
 	fprintf(OPF, "\n\n");
 }
diff --git a/src/bin/pg_dump/t/003_pg_dump_with_server.pl b/src/bin/pg_dump/t/003_pg_dump_with_server.pl
index 349add67d5..e0f2c31c52 100644
--- a/src/bin/pg_dump/t/003_pg_dump_with_server.pl
+++ b/src/bin/pg_dump/t/003_pg_dump_with_server.pl
@@ -47,4 +47,52 @@ command_ok(
 	],
 	"dump foreign server with no tables");
 
+# These grants can be made using an independent source of ADMIN OPTION that
+# is subsequently revoked. The final state cannot be replayed by ordering the
+# surviving GRANTs alone.
+$node->safe_psql(
+	'postgres', q{
+	CREATE ROLE regress_group;
+	CREATE ROLE regress_a;
+	CREATE ROLE "regress_b$grants$";
+	CREATE ROLE regress_c;
+	GRANT regress_group TO regress_a WITH ADMIN OPTION;
+	GRANT regress_group TO "regress_b$grants$" WITH ADMIN OPTION GRANTED BY regress_a;
+	GRANT regress_group TO "regress_b$grants$" WITH ADMIN OPTION;
+	GRANT regress_group TO regress_a WITH ADMIN OPTION GRANTED BY "regress_b$grants$";
+	GRANT regress_group TO regress_c WITH ADMIN OPTION, INHERIT FALSE;
+	GRANT regress_group TO regress_c WITH ADMIN OPTION, SET FALSE GRANTED BY regress_a;
+	GRANT regress_group TO "regress_b$grants$" WITH ADMIN OPTION GRANTED BY regress_c;
+	REVOKE regress_group FROM "regress_b$grants$" GRANTED BY CURRENT_USER;
+	REVOKE ADMIN OPTION FOR regress_group FROM regress_c GRANTED BY CURRENT_USER;
+});
+
+my $roles_file = "$tempdir/roles.sql";
+$node->command_ok(
+	[ 'pg_dumpall', '--roles-only', '--file', $roles_file ],
+	'dump circular ADMIN grants');
+
+my $memberships = q{
+	SELECT member::regrole::text, grantor::regrole::text,
+		admin_option, inherit_option, set_option
+	FROM pg_auth_members WHERE roleid = 'regress_group'::regrole
+	ORDER BY 1, 2};
+my $expected = $node->safe_psql('postgres', $memberships);
+
+my $restored = PostgreSQL::Test::Cluster->new('restored');
+$restored->init;
+$restored->start;
+# initdb already created the bootstrap superuser in the destination.
+my $bootstrap_create =
+  $node->safe_psql('postgres', q{SELECT format('CREATE ROLE %I;', current_user)});
+my $dump = slurp_file($roles_file);
+$dump =~ s/^\Q$bootstrap_create\E$//m or die 'missing bootstrap role in dump';
+$restored->safe_psql('postgres', "BEGIN;\n$dump\nROLLBACK;");
+is($restored->safe_psql('postgres',
+		q{SELECT count(*) FROM pg_roles WHERE rolname = 'regress_group'}),
+	0, 'restoring circular grants respects an outer transaction');
+$restored->safe_psql('postgres', $dump);
+is($restored->safe_psql('postgres', $memberships),
+	$expected, 'restore preserves circular grants, grantors, and grant options');
+
 done_testing();
