From 053f4a0a63fb8e561faf66af94f6f8f16ff737ad Mon Sep 17 00:00:00 2001
From: Jelte Fennema <jelte.fennema@microsoft.com>
Date: Thu, 12 Jan 2023 09:23:45 +0100
Subject: [PATCH v5 3/4] Only expand \1 in pg_ident.conf when not quoted

While unlikely, it's possible for usernames to contain the literal
character sequence '\1'. This allows quoting the database-username in
a pg_ident.conf file such that it's possible to match against a literal
'\1' character sequence.
---
 doc/src/sgml/client-auth.sgml         |  3 +++
 src/test/authentication/t/003_peer.pl | 12 ++++++++++++
 2 files changed, 15 insertions(+)

diff --git a/doc/src/sgml/client-auth.sgml b/doc/src/sgml/client-auth.sgml
index cc8c59206c9..50af2bf03b8 100644
--- a/doc/src/sgml/client-auth.sgml
+++ b/doc/src/sgml/client-auth.sgml
@@ -960,6 +960,9 @@ mymap   /^(.*)@otherdomain\.com$   guest
    will remove the domain part for users with system user names that end with
    <literal>@mydomain.com</literal>, and allow any user whose system name ends with
    <literal>@otherdomain.com</literal> to log in as <literal>guest</literal>.
+   Quoting a <replaceable>database-username</replaceable> containing
+   <literal>\1</literal> <emphasis>does not</emphasis> make <literal>\1</literal>
+   lose its special meaning.
   </para>
 
   <tip>
diff --git a/src/test/authentication/t/003_peer.pl b/src/test/authentication/t/003_peer.pl
index 966b2aa47ef..796fd059ccd 100644
--- a/src/test/authentication/t/003_peer.pl
+++ b/src/test/authentication/t/003_peer.pl
@@ -153,6 +153,18 @@ test_role(
 	log_like =>
 	  [qr/connection authenticated: identity="$system_user" method=peer/]);
 
+# Success as the regular expression matches and \1 is replaced in the given
+# subexpression, even in a quoted string.
+reset_pg_ident($node, 'mypeermap', qq{/^$system_user(.*)\$}, '"test\1mapuser"');
+test_role(
+	$node,
+	qq{testmapuser},
+	'peer',
+	0,
+	'with regular expression in user name map replacing a quoted \1',
+	log_like =>
+	  [qr/connection authenticated: identity="$system_user" method=peer/]);
+
 # Failure as the regular expression does not include a subexpression, but
 # the database user contains \1, requesting a replacement.
 reset_pg_ident($node, 'mypeermap', qq{/^$system_user\$}, '\1testmapuser');
-- 
2.34.1

