On Thu, Jun 23, 2022 at 10:33 AM Jacob Champion <jchamp...@timescale.com> wrote:
> - I think NOT is a important case in practice, which is effectively a
> negative OR ("anything but this/these")

Both NOT (via ! negation) and "none" are implemented in v4.

Examples:

# The server must use SCRAM.
require_auth=scram-sha-256
# The server must use SCRAM or Kerberos.
require_auth=scram-sha-256,gss,sspi
# The server may optionally use SCRAM.
require_auth=none,scram-sha-256
# The server must not use any application-level authentication.
require_auth=none
# The server may optionally use authentication, except plaintext
# passwords.
require_auth=!password
# The server may optionally use authentication, except weaker password
# challenges.
require_auth=!password,!md5
# The server must use an authentication method.
require_auth=!none
# The server must use a non-plaintext authentication method.
require_auth=!none,!password

Note that `require_auth=none,scram-sha-256` allows the server to
abandon a SCRAM exchange early, same as it can today. That might be a
bit surprising.

--Jacob
commit dcae9a7c1cef593055c932c85244852a119b0313
Author: Jacob Champion <jchamp...@timescale.com>
Date:   Thu Jun 23 15:38:12 2022 -0700

    squash! libpq: let client reject unexpected auth methods
    
    - Add "none" and method negation with "!".
    - Test unknown methods to round out coverage.
    
    TODO: should "none,scram-sha-256" allow an incomplete SCRAM handshake?

diff --git a/doc/src/sgml/libpq.sgml b/doc/src/sgml/libpq.sgml
index 00990ce47d..cc831158b7 100644
--- a/doc/src/sgml/libpq.sgml
+++ b/doc/src/sgml/libpq.sgml
@@ -1233,6 +1233,20 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname
         for the connection to succeed. By default, any authentication method is
         accepted, and the server is free to skip authentication altogether.
       </para>
+      <para>
+        Methods may be negated with the addition of a <literal>!</literal>
+        prefix, in which case the server must <emphasis>not</emphasis> attempt
+        the listed method; any other method is accepted, and the server is free
+        not to authenticate the client at all. If a comma-separated list is
+        provided, the server may not attempt <emphasis>any</emphasis> of the
+        listed negated methods. Negated and non-negated forms may not be
+        combined in the same setting.
+      </para>
+      <para>
+        As a final special case, the <literal>none</literal> method requires 
the
+        server not to use an authentication challenge. (It may also be negated,
+        to require some form of authentication.)
+      </para>
       <para>
         The following methods may be specified:
 
@@ -1286,6 +1300,17 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname
            </para>
           </listitem>
          </varlistentry>
+
+         <varlistentry>
+          <term><literal>none</literal></term>
+          <listitem>
+           <para>
+            The server must not prompt the client for an authentication
+            exchange. (This does not prohibit client certificate authentication
+                       via TLS, nor GSS authentication via its encrypted 
transport.)
+           </para>
+          </listitem>
+         </varlistentry>
         </variablelist>
       </para>
       </listitem>
diff --git a/src/interfaces/libpq/fe-auth.c b/src/interfaces/libpq/fe-auth.c
index 59c3575cc3..f789bc7ec3 100644
--- a/src/interfaces/libpq/fe-auth.c
+++ b/src/interfaces/libpq/fe-auth.c
@@ -902,9 +902,14 @@ check_expected_areq(AuthRequest areq, PGconn *conn)
                {
                        case AUTH_REQ_OK:
                                /*
-                                * Check to make sure we've actually finished 
our exchange.
+                                * Check to make sure we've actually finished 
our exchange (or
+                                * else that the user has allowed an 
authentication-less
+                                * connection).
+                                *
+                                * TODO: how should !auth_required interact 
with an incomplete
+                                * SCRAM exchange?
                                 */
-                               if (conn->client_finished_auth)
+                               if (!conn->auth_required || 
conn->client_finished_auth)
                                        break;
 
                                /*
diff --git a/src/interfaces/libpq/fe-connect.c 
b/src/interfaces/libpq/fe-connect.c
index f2579ff7ee..7d5bf337f6 100644
--- a/src/interfaces/libpq/fe-connect.c
+++ b/src/interfaces/libpq/fe-connect.c
@@ -1265,17 +1265,65 @@ connectOptions2(PGconn *conn)
        if (conn->require_auth)
        {
                char       *s = conn->require_auth;
-               bool            more = true;
+               bool            first, more;
+               bool            negated = false;
+
+               /*
+                * By default, start from an empty set of allowed options and 
add to it.
+                */
+               conn->auth_required = true;
+               conn->allowed_auth_methods = 0;
 
-               while (more)
+               for (first = true, more = true; more; first = false)
                {
-                       char       *method;
+                       char       *method, *part;
                        uint32          bits;
 
-                       method = parse_comma_separated_list(&s, &more);
-                       if (method == NULL)
+                       part = parse_comma_separated_list(&s, &more);
+                       if (part == NULL)
                                goto oom_error;
 
+                       /*
+                        * Check for negation, e.g. '!password'. If one element 
is negated,
+                        * they all have to be.
+                        */
+                       method = part;
+                       if (*method == '!')
+                       {
+                               if (first)
+                               {
+                                       /*
+                                        * Switch to a permissive set of 
allowed options, and
+                                        * subtract from it.
+                                        */
+                                       conn->auth_required = false;
+                                       conn->allowed_auth_methods = -1;
+                               }
+                               else if (!negated)
+                               {
+                                       conn->status = CONNECTION_BAD;
+                                       appendPQExpBuffer(&conn->errorMessage,
+                                                                         
libpq_gettext("negative require_auth method \"%s\" cannot be mixed with 
non-negative methods"),
+                                                                         
method);
+
+                                       free(part);
+                                       return false;
+                               }
+
+                               negated = true;
+                               method++;
+                       }
+                       else if (negated)
+                       {
+                               conn->status = CONNECTION_BAD;
+                               appendPQExpBuffer(&conn->errorMessage,
+                                                                 
libpq_gettext("require_auth method \"%s\" cannot be mixed with negative 
methods"),
+                                                                 method);
+
+                               free(part);
+                               return false;
+                       }
+
                        if (strcmp(method, "password") == 0)
                        {
                                bits = (1 << AUTH_REQ_PASSWORD);
@@ -1301,6 +1349,31 @@ connectOptions2(PGconn *conn)
                                bits |= (1 << AUTH_REQ_SASL_CONT);
                                bits |= (1 << AUTH_REQ_SASL_FIN);
                        }
+                       else if (strcmp(method, "none") == 0)
+                       {
+                               /*
+                                * Special case: let the user explicitly allow 
(or disallow)
+                                * connections where the server does not send 
an explicit
+                                * authentication challenge, such as "trust" 
and "cert" auth.
+                                */
+                               if (negated) /* "!none" */
+                               {
+                                       if (conn->auth_required)
+                                               goto duplicate;
+
+                                       conn->auth_required = true;
+                               }
+                               else /* "none" */
+                               {
+                                       if (!conn->auth_required)
+                                               goto duplicate;
+
+                                       conn->auth_required = false;
+                               }
+
+                               free(part);
+                               continue; /* avoid the bitmask manipulation 
below */
+                       }
                        else
                        {
                                conn->status = CONNECTION_BAD;
@@ -1308,27 +1381,41 @@ connectOptions2(PGconn *conn)
                                                                  
libpq_gettext("invalid require_auth method: \"%s\""),
                                                                  method);
 
-                               free(method);
+                               free(part);
                                return false;
                        }
 
-                       /*
-                        * Sanity check; a duplicated method probably indicates 
a typo in a
-                        * setting where typos are extremely risky.
-                        */
-                       if ((conn->allowed_auth_methods & bits) == bits)
+                       /* Update the bitmask. */
+                       if (negated)
                        {
-                               conn->status = CONNECTION_BAD;
-                               appendPQExpBuffer(&conn->errorMessage,
-                                                                 
libpq_gettext("require_auth method \"%s\" is specified more than once"),
-                                                                 method);
+                               if ((conn->allowed_auth_methods & bits) == 0)
+                                       goto duplicate;
 
-                               free(method);
-                               return false;
+                               conn->allowed_auth_methods &= ~bits;
                        }
+                       else
+                       {
+                               if ((conn->allowed_auth_methods & bits) == bits)
+                                       goto duplicate;
+
+                               conn->allowed_auth_methods |= bits;
+                       }
+
+                       free(part);
+                       continue;
 
-                       conn->allowed_auth_methods |= bits;
-                       free(method);
+duplicate:
+                       /*
+                        * A duplicated method probably indicates a typo in a 
setting where
+                        * typos are extremely risky.
+                        */
+                       conn->status = CONNECTION_BAD;
+                       appendPQExpBuffer(&conn->errorMessage,
+                                                         
libpq_gettext("require_auth method \"%s\" is specified more than once"),
+                                                         part);
+
+                       free(part);
+                       return false;
                }
        }
 
diff --git a/src/interfaces/libpq/libpq-int.h b/src/interfaces/libpq/libpq-int.h
index 6216af7f87..3278196eea 100644
--- a/src/interfaces/libpq/libpq-int.h
+++ b/src/interfaces/libpq/libpq-int.h
@@ -455,6 +455,7 @@ struct pg_conn
        bool            write_failed;   /* have we had a write failure on sock? 
*/
        char       *write_err_msg;      /* write error message, or NULL if OOM 
*/
 
+       bool            auth_required;  /* require an authentication challenge 
from the server? */
        uint32          allowed_auth_methods;   /* bitmask of acceptable 
AuthRequest codes */
 
        /* Transient state needed while establishing connection */
diff --git a/src/test/authentication/t/001_password.pl 
b/src/test/authentication/t/001_password.pl
index dd27092134..473a93d6db 100644
--- a/src/test/authentication/t/001_password.pl
+++ b/src/test/authentication/t/001_password.pl
@@ -82,12 +82,12 @@ test_role($node, 'scram_role', 'trust', 0,
 test_role($node, 'md5_role', 'trust', 0,
        log_unlike => [qr/connection authenticated:/]);
 
-# All require_auth options should fail.
+# All positive require_auth options should fail...
 $node->connect_fails("user=scram_role require_auth=gss",
        "GSS authentication can be required: fails with trust auth",
        expected_stderr => qr/server did not complete authentication/);
 $node->connect_fails("user=scram_role require_auth=sspi",
-       "GSS authentication can be required: fails with trust auth",
+       "SSPI authentication can be required: fails with trust auth",
        expected_stderr => qr/server did not complete authentication/);
 $node->connect_fails("user=scram_role require_auth=password",
        "password authentication can be required: fails with trust auth",
@@ -102,6 +102,54 @@ $node->connect_fails("user=scram_role 
require_auth=password,scram-sha-256",
        "multiple authentication types can be required: fails with trust auth",
        expected_stderr => qr/server did not complete authentication/);
 
+# ...and negative require_auth options should succeed.
+$node->connect_ok("user=scram_role require_auth=!gss",
+       "GSS authentication can be forbidden: succeeds with trust auth");
+$node->connect_ok("user=scram_role require_auth=!sspi",
+       "SSPI authentication can be forbidden: succeeds with trust auth");
+$node->connect_ok("user=scram_role require_auth=!password",
+       "password authentication can be forbidden: succeeds with trust auth");
+$node->connect_ok("user=scram_role require_auth=!md5",
+       "md5 authentication can be forbidden: succeeds with trust auth");
+$node->connect_ok("user=scram_role require_auth=!scram-sha-256",
+       "SCRAM authentication can be forbidden: succeeds with trust auth");
+$node->connect_ok("user=scram_role require_auth=!password,!scram-sha-256",
+       "multiple authentication types can be forbidden: succeeds with trust 
auth");
+
+# require_auth=[!]none should interact correctly with trust auth.
+$node->connect_ok("user=scram_role require_auth=none",
+       "all authentication can be forbidden: succeeds with trust auth");
+$node->connect_fails("user=scram_role require_auth=!none",
+       "any authentication can be required: fails with trust auth",
+       expected_stderr => qr/server did not complete authentication/);
+
+# Negative and positive require_auth options can't be mixed.
+$node->connect_fails("user=scram_role require_auth=scram-sha-256,!md5",
+       "negative require_auth methods can't be mixed with positive",
+       expected_stderr => qr/negative require_auth method "!md5" cannot be 
mixed with non-negative methods/);
+$node->connect_fails("user=scram_role require_auth=!password,scram-sha-256",
+       "positive require_auth methods can't be mixed with negative",
+       expected_stderr => qr/require_auth method "scram-sha-256" cannot be 
mixed with negative methods/);
+
+# require_auth methods can't be duplicated.
+$node->connect_fails("user=scram_role require_auth=password,md5,password",
+       "require_auth methods can't be duplicated: positive case",
+       expected_stderr => qr/require_auth method "password" is specified more 
than once/);
+$node->connect_fails("user=scram_role require_auth=!password,!md5,!password",
+       "require_auth methods can't be duplicated: negative case",
+       expected_stderr => qr/require_auth method "!password" is specified more 
than once/);
+$node->connect_fails("user=scram_role require_auth=none,md5,none",
+       "require_auth methods can't be duplicated: none case",
+       expected_stderr => qr/require_auth method "none" is specified more than 
once/);
+$node->connect_fails("user=scram_role require_auth=!none,!md5,!none",
+       "require_auth methods can't be duplicated: !none case",
+       expected_stderr => qr/require_auth method "!none" is specified more 
than once/);
+
+# Unknown require_auth methods are caught.
+$node->connect_fails("user=scram_role require_auth=none,abcdefg",
+       "unknown require_auth methods are rejected",
+       expected_stderr => qr/invalid require_auth method: "abcdefg"/);
+
 # For plain "password" method, all users should also be able to connect.
 reset_pg_hba($node, 'password');
 test_role($node, 'scram_role', 'password', 0,
@@ -114,16 +162,29 @@ test_role($node, 'md5_role', 'password', 0,
 # require_auth should succeed with a plaintext password...
 $node->connect_ok("user=scram_role require_auth=password",
        "password authentication can be required: works with password auth");
+$node->connect_ok("user=scram_role require_auth=!none",
+       "any authentication can be required: works with password auth");
 $node->connect_ok("user=scram_role require_auth=scram-sha-256,password,md5",
        "multiple authentication types can be required: works with password 
auth");
 
-# ...and fail for other auth types.
+# ...fail for other auth types...
 $node->connect_fails("user=scram_role require_auth=md5",
        "md5 authentication can be required: fails with password auth",
        expected_stderr => qr/server requested a cleartext password/);
 $node->connect_fails("user=scram_role require_auth=scram-sha-256",
        "SCRAM authentication can be required: fails with password auth",
        expected_stderr => qr/server requested a cleartext password/);
+$node->connect_fails("user=scram_role require_auth=none",
+       "all authentication can be forbidden: fails with password auth",
+       expected_stderr => qr/server requested a cleartext password/);
+
+# ...and allow password authentication to be prohibited.
+$node->connect_fails("user=scram_role require_auth=!password",
+       "password authentication can be forbidden: fails with password auth",
+       expected_stderr => qr/server requested a cleartext password/);
+$node->connect_fails("user=scram_role 
require_auth=!password,!md5,!scram-sha-256",
+       "multiple authentication types can be forbidden: fails with password 
auth",
+       expected_stderr => qr/server requested a cleartext password/);
 
 # For "scram-sha-256" method, user "scram_role" should be able to connect.
 reset_pg_hba($node, 'scram-sha-256');
@@ -141,16 +202,29 @@ test_role($node, 'md5_role', 'scram-sha-256', 2,
 # require_auth should succeed with SCRAM...
 $node->connect_ok("user=scram_role require_auth=scram-sha-256",
        "SCRAM authentication can be required: works with SCRAM auth");
+$node->connect_ok("user=scram_role require_auth=!none",
+       "any authentication can be required: works with SCRAM auth");
 $node->connect_ok("user=scram_role require_auth=password,scram-sha-256,md5",
        "multiple authentication types can be required: works with SCRAM auth");
 
-# ...and fail for other auth types.
+# ...fail for other auth types...
 $node->connect_fails("user=scram_role require_auth=password",
        "password authentication can be required: fails with SCRAM auth",
        expected_stderr => qr/server requested SASL authentication/);
 $node->connect_fails("user=scram_role require_auth=md5",
        "md5 authentication can be required: fails with SCRAM auth",
        expected_stderr => qr/server requested SASL authentication/);
+$node->connect_fails("user=scram_role require_auth=none",
+       "all authentication can be forbidden: fails with SCRAM auth",
+       expected_stderr => qr/server requested SASL authentication/);
+
+# ...and allow SCRAM authentication to be prohibited.
+$node->connect_fails("user=scram_role require_auth=!scram-sha-256",
+       "SCRAM authentication can be forbidden: fails with SCRAM auth",
+       expected_stderr => qr/server requested SASL authentication/);
+$node->connect_fails("user=scram_role 
require_auth=!password,!md5,!scram-sha-256",
+       "multiple authentication types can be forbidden: fails with SCRAM auth",
+       expected_stderr => qr/server requested SASL authentication/);
 
 # Test that bad passwords are rejected.
 $ENV{"PGPASSWORD"} = 'badpass';
@@ -171,16 +245,29 @@ test_role($node, 'md5_role', 'md5', 0,
 # require_auth should succeed with MD5...
 $node->connect_ok("user=md5_role require_auth=md5",
        "MD5 authentication can be required: works with MD5 auth");
+$node->connect_ok("user=md5_role require_auth=!none",
+       "any authentication can be required: works with MD5 auth");
 $node->connect_ok("user=md5_role require_auth=md5,scram-sha-256,password",
        "multiple authentication types can be required: works with MD5 auth");
 
-# ...and fail for other auth types.
+# ...fail for other auth types...
 $node->connect_fails("user=md5_role require_auth=password",
        "password authentication can be required: fails with MD5 auth",
        expected_stderr => qr/server requested a hashed password/);
 $node->connect_fails("user=md5_role require_auth=scram-sha-256",
        "SCRAM authentication can be required: fails with MD5 auth",
        expected_stderr => qr/server requested a hashed password/);
+$node->connect_fails("user=md5_role require_auth=none",
+       "all authentication can be forbidden: fails with MD5 auth",
+       expected_stderr => qr/server requested a hashed password/);
+
+# ...and allow MD5 authentication to be prohibited.
+$node->connect_fails("user=md5_role require_auth=!md5",
+       "password authentication can be forbidden: fails with MD5 auth",
+       expected_stderr => qr/server requested a hashed password/);
+$node->connect_fails("user=md5_role 
require_auth=!password,!md5,!scram-sha-256",
+       "multiple authentication types can be forbidden: fails with MD5 auth",
+       expected_stderr => qr/server requested a hashed password/);
 
 # Tests for channel binding without SSL.
 # Using the password authentication method; channel binding can't work
From fe629cbd21df83ac0065e9eb4ae88bffff19c429 Mon Sep 17 00:00:00 2001
From: Jacob Champion <pchamp...@vmware.com>
Date: Mon, 28 Feb 2022 09:40:43 -0800
Subject: [PATCH v4] libpq: let client reject unexpected auth methods

The require_auth connection option allows the client to choose a list of
acceptable authentication types for use with the server. There is no
negotiation: if the server does not present one of the allowed
authentication requests, the connection fails. Additionally, all methods
in the list may be negated, e.g. '!password', in which case the server
must NOT use the listed authentication type. The special method "none"
allows/disallows the use of unauthenticated connections (but it does not
govern transport-level authentication via TLS or GSSAPI).

Internally, the patch expands the role of check_expected_areq() to
ensure that the incoming request is compatible with conn->require_auth.
It also introduces a new flag, conn->client_finished_auth, which is set
by various authentication routines when the client side of the handshake
is finished. This signals to check_expected_areq() that an OK message
from the server is expected, and allows the client to complain if the
server forgoes authentication entirely.

(Since the client can't generally prove that the server is actually
doing the work of authentication, this last part is mostly useful for
SCRAM without channel binding. It could also provide a client with a
decent signal that, at the very least, it's not connecting to a database
with trust auth, and so the connection can be tied to the client in a
later audit.)

Deficiencies:
- This feature currently doesn't prevent unexpected certificate exchange
  or unexpected GSSAPI encryption.
- This is unlikely to be very forwards-compatible at the moment,
  especially with SASL/SCRAM.
- SSPI support is "implemented" but untested.
- require_auth=none,scram-sha-256 currently allows the server to leave a
  SCRAM exchange unfinished. This is not net-new behavior but may be
  surprising.
---
 doc/src/sgml/libpq.sgml                   | 105 ++++++++++++++
 src/include/libpq/pqcomm.h                |   1 +
 src/interfaces/libpq/fe-auth-scram.c      |   1 +
 src/interfaces/libpq/fe-auth.c            | 138 ++++++++++++++++++
 src/interfaces/libpq/fe-connect.c         | 164 ++++++++++++++++++++++
 src/interfaces/libpq/fe-secure-openssl.c  |   1 -
 src/interfaces/libpq/libpq-int.h          |   7 +
 src/test/authentication/t/001_password.pl | 149 ++++++++++++++++++++
 src/test/kerberos/t/001_auth.pl           |  26 ++++
 src/test/ldap/t/001_auth.pl               |   6 +
 src/test/ssl/t/002_scram.pl               |  25 ++++
 11 files changed, 622 insertions(+), 1 deletion(-)

diff --git a/doc/src/sgml/libpq.sgml b/doc/src/sgml/libpq.sgml
index 37ec3cb4e5..cc831158b7 100644
--- a/doc/src/sgml/libpq.sgml
+++ b/doc/src/sgml/libpq.sgml
@@ -1221,6 +1221,101 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname
       </listitem>
      </varlistentry>
 
+     <varlistentry id="libpq-connect-require-auth" xreflabel="require_auth">
+      <term><literal>require_auth</literal></term>
+      <listitem>
+      <para>
+        Specifies the authentication method that the client requires from the
+        server. If the server does not use the required method to authenticate
+        the client, or if the authentication handshake is not fully completed by
+        the server, the connection will fail. A comma-separated list of methods
+        may also be provided, of which the server must use exactly one in order
+        for the connection to succeed. By default, any authentication method is
+        accepted, and the server is free to skip authentication altogether.
+      </para>
+      <para>
+        Methods may be negated with the addition of a <literal>!</literal>
+        prefix, in which case the server must <emphasis>not</emphasis> attempt
+        the listed method; any other method is accepted, and the server is free
+        not to authenticate the client at all. If a comma-separated list is
+        provided, the server may not attempt <emphasis>any</emphasis> of the
+        listed negated methods. Negated and non-negated forms may not be
+        combined in the same setting.
+      </para>
+      <para>
+        As a final special case, the <literal>none</literal> method requires the
+        server not to use an authentication challenge. (It may also be negated,
+        to require some form of authentication.)
+      </para>
+      <para>
+        The following methods may be specified:
+
+        <variablelist>
+         <varlistentry>
+          <term><literal>password</literal></term>
+          <listitem>
+           <para>
+            The server must request plaintext password authentication.
+           </para>
+          </listitem>
+         </varlistentry>
+
+         <varlistentry>
+          <term><literal>md5</literal></term>
+          <listitem>
+           <para>
+            The server must request MD5 hashed password authentication.
+           </para>
+          </listitem>
+         </varlistentry>
+
+         <varlistentry>
+          <term><literal>gss</literal></term>
+          <listitem>
+           <para>
+            The server must either request a Kerberos handshake via
+            <acronym>GSSAPI</acronym> or establish a
+            <acronym>GSS</acronym>-encrypted channel (see also
+            <xref linkend="libpq-connect-gssencmode" />).
+           </para>
+          </listitem>
+         </varlistentry>
+
+         <varlistentry>
+          <term><literal>sspi</literal></term>
+          <listitem>
+           <para>
+            The server must request Windows <acronym>SSPI</acronym>
+            authentication.
+           </para>
+          </listitem>
+         </varlistentry>
+
+         <varlistentry>
+          <term><literal>scram-sha-256</literal></term>
+          <listitem>
+           <para>
+            The server must successfully complete a SCRAM-SHA-256 authentication
+            exchange with the client.
+           </para>
+          </listitem>
+         </varlistentry>
+
+         <varlistentry>
+          <term><literal>none</literal></term>
+          <listitem>
+           <para>
+            The server must not prompt the client for an authentication
+            exchange. (This does not prohibit client certificate authentication
+			via TLS, nor GSS authentication via its encrypted transport.)
+           </para>
+          </listitem>
+         </varlistentry>
+        </variablelist>
+      </para>
+      </listitem>
+     </varlistentry>
+
      <varlistentry id="libpq-connect-channel-binding" xreflabel="channel_binding">
       <term><literal>channel_binding</literal></term>
       <listitem>
@@ -7761,6 +7856,16 @@ myEventProc(PGEventId evtId, void *evtInfo, void *passThrough)
      </para>
     </listitem>
 
+    <listitem>
+     <para>
+      <indexterm>
+       <primary><envar>PGREQUIREAUTH</envar></primary>
+      </indexterm>
+      <envar>PGREQUIREAUTH</envar> behaves the same as the <xref
+      linkend="libpq-connect-require-auth"/> connection parameter.
+     </para>
+    </listitem>
+
     <listitem>
      <para>
       <indexterm>
diff --git a/src/include/libpq/pqcomm.h b/src/include/libpq/pqcomm.h
index b418283d5f..a47f7b2d91 100644
--- a/src/include/libpq/pqcomm.h
+++ b/src/include/libpq/pqcomm.h
@@ -161,6 +161,7 @@ extern PGDLLIMPORT bool Db_user_namespace;
 #define AUTH_REQ_SASL	   10	/* Begin SASL authentication */
 #define AUTH_REQ_SASL_CONT 11	/* Continue SASL authentication */
 #define AUTH_REQ_SASL_FIN  12	/* Final SASL message */
+#define AUTH_REQ_MAX	   AUTH_REQ_SASL_FIN	/* maximum AUTH_REQ_* value */
 
 typedef uint32 AuthRequest;
 
diff --git a/src/interfaces/libpq/fe-auth-scram.c b/src/interfaces/libpq/fe-auth-scram.c
index e616200704..d918e8b87f 100644
--- a/src/interfaces/libpq/fe-auth-scram.c
+++ b/src/interfaces/libpq/fe-auth-scram.c
@@ -289,6 +289,7 @@ scram_exchange(void *opaq, char *input, int inputlen,
 			}
 			*done = true;
 			state->state = FE_SCRAM_FINISHED;
+			state->conn->client_finished_auth = true;
 			break;
 
 		default:
diff --git a/src/interfaces/libpq/fe-auth.c b/src/interfaces/libpq/fe-auth.c
index 0a072a36dc..f789bc7ec3 100644
--- a/src/interfaces/libpq/fe-auth.c
+++ b/src/interfaces/libpq/fe-auth.c
@@ -138,7 +138,10 @@ pg_GSS_continue(PGconn *conn, int payloadlen)
 	}
 
 	if (maj_stat == GSS_S_COMPLETE)
+	{
+		conn->client_finished_auth = true;
 		gss_release_name(&lmin_s, &conn->gtarg_nam);
+	}
 
 	return STATUS_OK;
 }
@@ -328,6 +331,9 @@ pg_SSPI_continue(PGconn *conn, int payloadlen)
 		FreeContextBuffer(outbuf.pBuffers[0].pvBuffer);
 	}
 
+	if (r == SEC_E_OK)
+		conn->client_finished_auth = true;
+
 	/* Cleanup is handled by the code in freePGconn() */
 	return STATUS_OK;
 }
@@ -836,6 +842,44 @@ pg_password_sendauth(PGconn *conn, const char *password, AuthRequest areq)
 	return ret;
 }
 
+/*
+ * Translate an AuthRequest into a human-readable description.
+ */
+static const char *
+auth_description(AuthRequest areq)
+{
+	switch (areq)
+	{
+		case AUTH_REQ_PASSWORD:
+			return libpq_gettext("a cleartext password");
+		case AUTH_REQ_MD5:
+			return libpq_gettext("a hashed password");
+		case AUTH_REQ_GSS:
+		case AUTH_REQ_GSS_CONT:
+			return libpq_gettext("GSSAPI authentication");
+		case AUTH_REQ_SSPI:
+			return libpq_gettext("SSPI authentication");
+		case AUTH_REQ_SCM_CREDS:
+			return libpq_gettext("UNIX socket credentials");
+		case AUTH_REQ_SASL:
+		case AUTH_REQ_SASL_CONT:
+		case AUTH_REQ_SASL_FIN:
+			return libpq_gettext("SASL authentication");
+	}
+
+	return libpq_gettext("an unknown authentication type");
+}
+
+/*
+ * Convenience macro for checking the allowed_auth_methods bitmask. Caller must
+ * ensure that type is not greater than 31 (high bit of the bitmask).
+ */
+#define auth_allowed(conn, type) \
+	(((conn)->allowed_auth_methods & (1 << (type))) != 0)
+
+StaticAssertDecl(AUTH_REQ_MAX < CHAR_BIT * sizeof(((PGconn){0}).allowed_auth_methods),
+				 "AUTH_REQ_MAX overflows the allowed_auth_methods bitmask");
+
 /*
  * Verify that the authentication request is expected, given the connection
  * parameters. This is especially important when the client wishes to
@@ -845,6 +889,97 @@ static bool
 check_expected_areq(AuthRequest areq, PGconn *conn)
 {
 	bool		result = true;
+	char	   *reason = NULL;
+
+	/*
+	 * If the user required a specific auth method, or specified an allowed set,
+	 * then reject all others here, and make sure the server actually completes
+	 * an authentication exchange.
+	 */
+	if (conn->require_auth)
+	{
+		switch (areq)
+		{
+			case AUTH_REQ_OK:
+				/*
+				 * Check to make sure we've actually finished our exchange (or
+				 * else that the user has allowed an authentication-less
+				 * connection).
+				 *
+				 * TODO: how should !auth_required interact with an incomplete
+				 * SCRAM exchange?
+				 */
+				if (!conn->auth_required || conn->client_finished_auth)
+					break;
+
+				/*
+				 * No explicit authentication request was made by the server --
+				 * or perhaps it was made and not completed, in the case of
+				 * SCRAM -- but there is one special case to check. If the user
+				 * allowed "gss", then a GSS-encrypted channel also satisfies
+				 * the check.
+				 */
+#ifdef ENABLE_GSS
+				if (auth_allowed(conn, AUTH_REQ_GSS) && conn->gssenc)
+				{
+					/*
+					 * If implicit GSS auth has already been performed via GSS
+					 * encryption, we don't need to have performed an
+					 * AUTH_REQ_GSS exchange.
+					 *
+					 * TODO: check this assumption. What mutual auth guarantees
+					 * are made in this case?
+					 */
+				}
+				else
+#endif
+				{
+					reason = libpq_gettext("server did not complete authentication"),
+					result = false;
+				}
+
+				break;
+
+			case AUTH_REQ_PASSWORD:
+			case AUTH_REQ_MD5:
+			case AUTH_REQ_GSS:
+			case AUTH_REQ_SSPI:
+			case AUTH_REQ_GSS_CONT:
+			case AUTH_REQ_SASL:
+			case AUTH_REQ_SASL_CONT:
+			case AUTH_REQ_SASL_FIN:
+				/*
+				 * We don't handle these with the default case, to avoid
+				 * bit-shifting past the end of the allowed_auth_methods mask if
+				 * the server sends an unexpected AuthRequest.
+				 */
+				result = auth_allowed(conn, areq);
+				break;
+
+			default:
+				result = false;
+				break;
+		}
+	}
+
+	if (!result)
+	{
+		if (reason)
+		{
+			appendPQExpBuffer(&conn->errorMessage,
+							  libpq_gettext("auth method \"%s\" requirement failed: %s\n"),
+							  conn->require_auth, reason);
+		}
+		else
+		{
+			appendPQExpBuffer(&conn->errorMessage,
+							  libpq_gettext("auth method \"%s\" required, but server requested %s\n"),
+							  conn->require_auth,
+							  auth_description(areq));
+		}
+
+		return result;
+	}
 
 	/*
 	 * When channel_binding=require, we must protect against two cases: (1) we
@@ -1046,6 +1181,9 @@ pg_fe_sendauth(AuthRequest areq, int payloadlen, PGconn *conn)
 										 "fe_sendauth: error sending password authentication\n");
 					return STATUS_ERROR;
 				}
+
+				/* We expect no further authentication requests. */
+				conn->client_finished_auth = true;
 				break;
 			}
 
diff --git a/src/interfaces/libpq/fe-connect.c b/src/interfaces/libpq/fe-connect.c
index 6e936bbff3..7d5bf337f6 100644
--- a/src/interfaces/libpq/fe-connect.c
+++ b/src/interfaces/libpq/fe-connect.c
@@ -310,6 +310,10 @@ static const internalPQconninfoOption PQconninfoOptions[] = {
 		"Require-Peer", "", 10,
 	offsetof(struct pg_conn, requirepeer)},
 
+	{"require_auth", "PGREQUIREAUTH", NULL, NULL,
+		"Require-Auth", "", 14, /* sizeof("scram-sha-256") == 14 */
+	offsetof(struct pg_conn, require_auth)},
+
 	{"ssl_min_protocol_version", "PGSSLMINPROTOCOLVERSION", "TLSv1.2", NULL,
 		"SSL-Minimum-Protocol-Version", "", 8,	/* sizeof("TLSv1.x") == 8 */
 	offsetof(struct pg_conn, ssl_min_protocol_version)},
@@ -1255,6 +1259,166 @@ connectOptions2(PGconn *conn)
 		}
 	}
 
+	/*
+	 * parse and validate require_auth option
+	 */
+	if (conn->require_auth)
+	{
+		char	   *s = conn->require_auth;
+		bool		first, more;
+		bool		negated = false;
+
+		/*
+		 * By default, start from an empty set of allowed options and add to it.
+		 */
+		conn->auth_required = true;
+		conn->allowed_auth_methods = 0;
+
+		for (first = true, more = true; more; first = false)
+		{
+			char	   *method, *part;
+			uint32		bits;
+
+			part = parse_comma_separated_list(&s, &more);
+			if (part == NULL)
+				goto oom_error;
+
+			/*
+			 * Check for negation, e.g. '!password'. If one element is negated,
+			 * they all have to be.
+			 */
+			method = part;
+			if (*method == '!')
+			{
+				if (first)
+				{
+					/*
+					 * Switch to a permissive set of allowed options, and
+					 * subtract from it.
+					 */
+					conn->auth_required = false;
+					conn->allowed_auth_methods = -1;
+				}
+				else if (!negated)
+				{
+					conn->status = CONNECTION_BAD;
+					appendPQExpBuffer(&conn->errorMessage,
+									  libpq_gettext("negative require_auth method \"%s\" cannot be mixed with non-negative methods"),
+									  method);
+
+					free(part);
+					return false;
+				}
+
+				negated = true;
+				method++;
+			}
+			else if (negated)
+			{
+				conn->status = CONNECTION_BAD;
+				appendPQExpBuffer(&conn->errorMessage,
+								  libpq_gettext("require_auth method \"%s\" cannot be mixed with negative methods"),
+								  method);
+
+				free(part);
+				return false;
+			}
+
+			if (strcmp(method, "password") == 0)
+			{
+				bits = (1 << AUTH_REQ_PASSWORD);
+			}
+			else if (strcmp(method, "md5") == 0)
+			{
+				bits = (1 << AUTH_REQ_MD5);
+			}
+			else if (strcmp(method, "gss") == 0)
+			{
+				bits = (1 << AUTH_REQ_GSS);
+				bits |= (1 << AUTH_REQ_GSS_CONT);
+			}
+			else if (strcmp(method, "sspi") == 0)
+			{
+				bits = (1 << AUTH_REQ_SSPI);
+				bits |= (1 << AUTH_REQ_GSS_CONT);
+			}
+			else if (strcmp(method, "scram-sha-256") == 0)
+			{
+				/* This currently assumes that SCRAM is the only SASL method. */
+				bits = (1 << AUTH_REQ_SASL);
+				bits |= (1 << AUTH_REQ_SASL_CONT);
+				bits |= (1 << AUTH_REQ_SASL_FIN);
+			}
+			else if (strcmp(method, "none") == 0)
+			{
+				/*
+				 * Special case: let the user explicitly allow (or disallow)
+				 * connections where the server does not send an explicit
+				 * authentication challenge, such as "trust" and "cert" auth.
+				 */
+				if (negated) /* "!none" */
+				{
+					if (conn->auth_required)
+						goto duplicate;
+
+					conn->auth_required = true;
+				}
+				else /* "none" */
+				{
+					if (!conn->auth_required)
+						goto duplicate;
+
+					conn->auth_required = false;
+				}
+
+				free(part);
+				continue; /* avoid the bitmask manipulation below */
+			}
+			else
+			{
+				conn->status = CONNECTION_BAD;
+				appendPQExpBuffer(&conn->errorMessage,
+								  libpq_gettext("invalid require_auth method: \"%s\""),
+								  method);
+
+				free(part);
+				return false;
+			}
+
+			/* Update the bitmask. */
+			if (negated)
+			{
+				if ((conn->allowed_auth_methods & bits) == 0)
+					goto duplicate;
+
+				conn->allowed_auth_methods &= ~bits;
+			}
+			else
+			{
+				if ((conn->allowed_auth_methods & bits) == bits)
+					goto duplicate;
+
+				conn->allowed_auth_methods |= bits;
+			}
+
+			free(part);
+			continue;
+
+duplicate:
+			/*
+			 * A duplicated method probably indicates a typo in a setting where
+			 * typos are extremely risky.
+			 */
+			conn->status = CONNECTION_BAD;
+			appendPQExpBuffer(&conn->errorMessage,
+							  libpq_gettext("require_auth method \"%s\" is specified more than once"),
+							  part);
+
+			free(part);
+			return false;
+		}
+	}
+
 	/*
 	 * validate channel_binding option
 	 */
diff --git a/src/interfaces/libpq/fe-secure-openssl.c b/src/interfaces/libpq/fe-secure-openssl.c
index 8117cbd40f..fc91cae7a2 100644
--- a/src/interfaces/libpq/fe-secure-openssl.c
+++ b/src/interfaces/libpq/fe-secure-openssl.c
@@ -477,7 +477,6 @@ verify_cb(int ok, X509_STORE_CTX *ctx)
 	return ok;
 }
 
-
 /*
  * OpenSSL-specific wrapper around
  * pq_verify_peer_name_matches_certificate_name(), converting the ASN1_STRING
diff --git a/src/interfaces/libpq/libpq-int.h b/src/interfaces/libpq/libpq-int.h
index 3db6a17db4..3278196eea 100644
--- a/src/interfaces/libpq/libpq-int.h
+++ b/src/interfaces/libpq/libpq-int.h
@@ -393,6 +393,7 @@ struct pg_conn
 	char	   *ssl_min_protocol_version;	/* minimum TLS protocol version */
 	char	   *ssl_max_protocol_version;	/* maximum TLS protocol version */
 	char	   *target_session_attrs;	/* desired session properties */
+	char	   *require_auth;	/* name of the expected auth method */
 
 	/* Optional file to write trace info to */
 	FILE	   *Pfdebug;
@@ -454,6 +455,9 @@ struct pg_conn
 	bool		write_failed;	/* have we had a write failure on sock? */
 	char	   *write_err_msg;	/* write error message, or NULL if OOM */
 
+	bool		auth_required;	/* require an authentication challenge from the server? */
+	uint32		allowed_auth_methods;	/* bitmask of acceptable AuthRequest codes */
+
 	/* Transient state needed while establishing connection */
 	PGTargetServerType target_server_type;	/* desired session properties */
 	bool		try_next_addr;	/* time to advance to next address/host? */
@@ -509,6 +513,9 @@ struct pg_conn
 	bool		error_result;	/* do we need to make an ERROR result? */
 	PGresult   *next_result;	/* next result (used in single-row mode) */
 
+	bool		client_finished_auth; /* have we finished our half of the
+									   * authentication exchange? */
+
 	/* Assorted state for SASL, SSL, GSS, etc */
 	const pg_fe_sasl_mech *sasl;
 	void	   *sasl_state;
diff --git a/src/test/authentication/t/001_password.pl b/src/test/authentication/t/001_password.pl
index 3e3079c824..473a93d6db 100644
--- a/src/test/authentication/t/001_password.pl
+++ b/src/test/authentication/t/001_password.pl
@@ -82,6 +82,74 @@ test_role($node, 'scram_role', 'trust', 0,
 test_role($node, 'md5_role', 'trust', 0,
 	log_unlike => [qr/connection authenticated:/]);
 
+# All positive require_auth options should fail...
+$node->connect_fails("user=scram_role require_auth=gss",
+	"GSS authentication can be required: fails with trust auth",
+	expected_stderr => qr/server did not complete authentication/);
+$node->connect_fails("user=scram_role require_auth=sspi",
+	"SSPI authentication can be required: fails with trust auth",
+	expected_stderr => qr/server did not complete authentication/);
+$node->connect_fails("user=scram_role require_auth=password",
+	"password authentication can be required: fails with trust auth",
+	expected_stderr => qr/server did not complete authentication/);
+$node->connect_fails("user=scram_role require_auth=md5",
+	"md5 authentication can be required: fails with trust auth",
+	expected_stderr => qr/server did not complete authentication/);
+$node->connect_fails("user=scram_role require_auth=scram-sha-256",
+	"SCRAM authentication can be required: fails with trust auth",
+	expected_stderr => qr/server did not complete authentication/);
+$node->connect_fails("user=scram_role require_auth=password,scram-sha-256",
+	"multiple authentication types can be required: fails with trust auth",
+	expected_stderr => qr/server did not complete authentication/);
+
+# ...and negative require_auth options should succeed.
+$node->connect_ok("user=scram_role require_auth=!gss",
+	"GSS authentication can be forbidden: succeeds with trust auth");
+$node->connect_ok("user=scram_role require_auth=!sspi",
+	"SSPI authentication can be forbidden: succeeds with trust auth");
+$node->connect_ok("user=scram_role require_auth=!password",
+	"password authentication can be forbidden: succeeds with trust auth");
+$node->connect_ok("user=scram_role require_auth=!md5",
+	"md5 authentication can be forbidden: succeeds with trust auth");
+$node->connect_ok("user=scram_role require_auth=!scram-sha-256",
+	"SCRAM authentication can be forbidden: succeeds with trust auth");
+$node->connect_ok("user=scram_role require_auth=!password,!scram-sha-256",
+	"multiple authentication types can be forbidden: succeeds with trust auth");
+
+# require_auth=[!]none should interact correctly with trust auth.
+$node->connect_ok("user=scram_role require_auth=none",
+	"all authentication can be forbidden: succeeds with trust auth");
+$node->connect_fails("user=scram_role require_auth=!none",
+	"any authentication can be required: fails with trust auth",
+	expected_stderr => qr/server did not complete authentication/);
+
+# Negative and positive require_auth options can't be mixed.
+$node->connect_fails("user=scram_role require_auth=scram-sha-256,!md5",
+	"negative require_auth methods can't be mixed with positive",
+	expected_stderr => qr/negative require_auth method "!md5" cannot be mixed with non-negative methods/);
+$node->connect_fails("user=scram_role require_auth=!password,scram-sha-256",
+	"positive require_auth methods can't be mixed with negative",
+	expected_stderr => qr/require_auth method "scram-sha-256" cannot be mixed with negative methods/);
+
+# require_auth methods can't be duplicated.
+$node->connect_fails("user=scram_role require_auth=password,md5,password",
+	"require_auth methods can't be duplicated: positive case",
+	expected_stderr => qr/require_auth method "password" is specified more than once/);
+$node->connect_fails("user=scram_role require_auth=!password,!md5,!password",
+	"require_auth methods can't be duplicated: negative case",
+	expected_stderr => qr/require_auth method "!password" is specified more than once/);
+$node->connect_fails("user=scram_role require_auth=none,md5,none",
+	"require_auth methods can't be duplicated: none case",
+	expected_stderr => qr/require_auth method "none" is specified more than once/);
+$node->connect_fails("user=scram_role require_auth=!none,!md5,!none",
+	"require_auth methods can't be duplicated: !none case",
+	expected_stderr => qr/require_auth method "!none" is specified more than once/);
+
+# Unknown require_auth methods are caught.
+$node->connect_fails("user=scram_role require_auth=none,abcdefg",
+	"unknown require_auth methods are rejected",
+	expected_stderr => qr/invalid require_auth method: "abcdefg"/);
+
 # For plain "password" method, all users should also be able to connect.
 reset_pg_hba($node, 'password');
 test_role($node, 'scram_role', 'password', 0,
@@ -91,6 +159,33 @@ test_role($node, 'md5_role', 'password', 0,
 	log_like =>
 	  [qr/connection authenticated: identity="md5_role" method=password/]);
 
+# require_auth should succeed with a plaintext password...
+$node->connect_ok("user=scram_role require_auth=password",
+	"password authentication can be required: works with password auth");
+$node->connect_ok("user=scram_role require_auth=!none",
+	"any authentication can be required: works with password auth");
+$node->connect_ok("user=scram_role require_auth=scram-sha-256,password,md5",
+	"multiple authentication types can be required: works with password auth");
+
+# ...fail for other auth types...
+$node->connect_fails("user=scram_role require_auth=md5",
+	"md5 authentication can be required: fails with password auth",
+	expected_stderr => qr/server requested a cleartext password/);
+$node->connect_fails("user=scram_role require_auth=scram-sha-256",
+	"SCRAM authentication can be required: fails with password auth",
+	expected_stderr => qr/server requested a cleartext password/);
+$node->connect_fails("user=scram_role require_auth=none",
+	"all authentication can be forbidden: fails with password auth",
+	expected_stderr => qr/server requested a cleartext password/);
+
+# ...and allow password authentication to be prohibited.
+$node->connect_fails("user=scram_role require_auth=!password",
+	"password authentication can be forbidden: fails with password auth",
+	expected_stderr => qr/server requested a cleartext password/);
+$node->connect_fails("user=scram_role require_auth=!password,!md5,!scram-sha-256",
+	"multiple authentication types can be forbidden: fails with password auth",
+	expected_stderr => qr/server requested a cleartext password/);
+
 # For "scram-sha-256" method, user "scram_role" should be able to connect.
 reset_pg_hba($node, 'scram-sha-256');
 test_role(
@@ -104,6 +199,33 @@ test_role(
 test_role($node, 'md5_role', 'scram-sha-256', 2,
 	log_unlike => [qr/connection authenticated:/]);
 
+# require_auth should succeed with SCRAM...
+$node->connect_ok("user=scram_role require_auth=scram-sha-256",
+	"SCRAM authentication can be required: works with SCRAM auth");
+$node->connect_ok("user=scram_role require_auth=!none",
+	"any authentication can be required: works with SCRAM auth");
+$node->connect_ok("user=scram_role require_auth=password,scram-sha-256,md5",
+	"multiple authentication types can be required: works with SCRAM auth");
+
+# ...fail for other auth types...
+$node->connect_fails("user=scram_role require_auth=password",
+	"password authentication can be required: fails with SCRAM auth",
+	expected_stderr => qr/server requested SASL authentication/);
+$node->connect_fails("user=scram_role require_auth=md5",
+	"md5 authentication can be required: fails with SCRAM auth",
+	expected_stderr => qr/server requested SASL authentication/);
+$node->connect_fails("user=scram_role require_auth=none",
+	"all authentication can be forbidden: fails with SCRAM auth",
+	expected_stderr => qr/server requested SASL authentication/);
+
+# ...and allow SCRAM authentication to be prohibited.
+$node->connect_fails("user=scram_role require_auth=!scram-sha-256",
+	"SCRAM authentication can be forbidden: fails with SCRAM auth",
+	expected_stderr => qr/server requested SASL authentication/);
+$node->connect_fails("user=scram_role require_auth=!password,!md5,!scram-sha-256",
+	"multiple authentication types can be forbidden: fails with SCRAM auth",
+	expected_stderr => qr/server requested SASL authentication/);
+
 # Test that bad passwords are rejected.
 $ENV{"PGPASSWORD"} = 'badpass';
 test_role($node, 'scram_role', 'scram-sha-256', 2,
@@ -120,6 +242,33 @@ test_role($node, 'md5_role', 'md5', 0,
 	log_like =>
 	  [qr/connection authenticated: identity="md5_role" method=md5/]);
 
+# require_auth should succeed with MD5...
+$node->connect_ok("user=md5_role require_auth=md5",
+	"MD5 authentication can be required: works with MD5 auth");
+$node->connect_ok("user=md5_role require_auth=!none",
+	"any authentication can be required: works with MD5 auth");
+$node->connect_ok("user=md5_role require_auth=md5,scram-sha-256,password",
+	"multiple authentication types can be required: works with MD5 auth");
+
+# ...fail for other auth types...
+$node->connect_fails("user=md5_role require_auth=password",
+	"password authentication can be required: fails with MD5 auth",
+	expected_stderr => qr/server requested a hashed password/);
+$node->connect_fails("user=md5_role require_auth=scram-sha-256",
+	"SCRAM authentication can be required: fails with MD5 auth",
+	expected_stderr => qr/server requested a hashed password/);
+$node->connect_fails("user=md5_role require_auth=none",
+	"all authentication can be forbidden: fails with MD5 auth",
+	expected_stderr => qr/server requested a hashed password/);
+
+# ...and allow MD5 authentication to be prohibited.
+$node->connect_fails("user=md5_role require_auth=!md5",
+	"password authentication can be forbidden: fails with MD5 auth",
+	expected_stderr => qr/server requested a hashed password/);
+$node->connect_fails("user=md5_role require_auth=!password,!md5,!scram-sha-256",
+	"multiple authentication types can be forbidden: fails with MD5 auth",
+	expected_stderr => qr/server requested a hashed password/);
+
 # Tests for channel binding without SSL.
 # Using the password authentication method; channel binding can't work
 reset_pg_hba($node, 'password');
diff --git a/src/test/kerberos/t/001_auth.pl b/src/test/kerberos/t/001_auth.pl
index 62e0542639..de4ddcbf69 100644
--- a/src/test/kerberos/t/001_auth.pl
+++ b/src/test/kerberos/t/001_auth.pl
@@ -307,6 +307,24 @@ test_query(
 	'gssencmode=require',
 	'sending 100K lines works');
 
+# require_auth=gss should succeed...
+$node->connect_ok(
+	$node->connstr('postgres') . " user=test1 host=$host hostaddr=$hostaddr gssencmode=disable require_auth=gss",
+	"GSS authentication can be requested: works with GSS auth without encryption");
+$node->connect_ok(
+	$node->connstr('postgres') . " user=test1 host=$host hostaddr=$hostaddr gssencmode=require require_auth=gss",
+	"GSS authentication can be requested: works with GSS auth with encryption");
+
+# ...and require_auth=sspi should fail.
+$node->connect_fails(
+	$node->connstr('postgres') . " user=test1 host=$host hostaddr=$hostaddr gssencmode=disable require_auth=sspi",
+	"SSPI authentication can be requested: fails with GSS auth without encryption",
+	expected_stderr => qr/server requested GSSAPI authentication/);
+$node->connect_fails(
+	$node->connstr('postgres') . " user=test1 host=$host hostaddr=$hostaddr gssencmode=require require_auth=sspi",
+	"SSPI authentication can be requested: fails with GSS auth with encryption",
+	expected_stderr => qr/server did not complete authentication/);
+
 unlink($node->data_dir . '/pg_hba.conf');
 $node->append_conf('pg_hba.conf',
 	qq{hostgssenc all all $hostaddr/32 gss map=mymap});
@@ -335,6 +353,14 @@ test_access(
 test_access($node, 'test1', 'SELECT true', 2, 'gssencmode=disable',
 	'fails with GSS encryption disabled and hostgssenc hba');
 
+# require_auth=gss should succeed.
+$node->connect_ok(
+	$node->connstr('postgres') . " user=test1 host=$host hostaddr=$hostaddr gssencmode=require require_auth=gss",
+	"GSS authentication can be requested: works with GSS encryption");
+$node->connect_ok(
+	$node->connstr('postgres') . " user=test1 host=$host hostaddr=$hostaddr gssencmode=require require_auth=gss,scram-sha-256",
+	"multiple authentication types can be requested: works with GSS encryption");
+
 unlink($node->data_dir . '/pg_hba.conf');
 $node->append_conf('pg_hba.conf',
 	qq{hostnogssenc all all $hostaddr/32 gss map=mymap});
diff --git a/src/test/ldap/t/001_auth.pl b/src/test/ldap/t/001_auth.pl
index 86dff8bd1f..e7c67920a1 100644
--- a/src/test/ldap/t/001_auth.pl
+++ b/src/test/ldap/t/001_auth.pl
@@ -216,6 +216,12 @@ test_access(
 		qr/connection authenticated: identity="uid=test1,dc=example,dc=net" method=ldap/
 	],);
 
+# require_auth=password should complete successfully; other methods should fail.
+$node->connect_ok("user=test1 require_auth=password",
+	"password authentication can be required: works with ldap auth");
+$node->connect_fails("user=test1 require_auth=scram-sha-256",
+	"SCRAM authentication can be required: fails with ldap auth");
+
 note "search+bind";
 
 unlink($node->data_dir . '/pg_hba.conf');
diff --git a/src/test/ssl/t/002_scram.pl b/src/test/ssl/t/002_scram.pl
index 588f47a39b..9957a96e69 100644
--- a/src/test/ssl/t/002_scram.pl
+++ b/src/test/ssl/t/002_scram.pl
@@ -132,4 +132,29 @@ $node->connect_ok(
 		qr/connection authenticated: identity="ssltestuser" method=scram-sha-256/
 	]);
 
+# channel_binding should continue to function independently of require_auth.
+$node->connect_ok("$common_connstr user=ssltestuser channel_binding=disable require_auth=scram-sha-256",
+	"SCRAM with SSL, channel_binding=disable, and require_auth=scram-sha-256");
+$node->connect_fails(
+	"$common_connstr user=md5testuser require_auth=md5 channel_binding=require",
+	"channel_binding can fail even when require_auth succeeds",
+	expected_stderr =>
+	  qr/channel binding required but not supported by server's authentication request/
+);
+if ($supports_tls_server_end_point)
+{
+	$node->connect_ok(
+		"$common_connstr user=ssltestuser channel_binding=require require_auth=scram-sha-256",
+		"SCRAM with SSL, channel_binding=require, and require_auth=scram-sha-256");
+}
+else
+{
+	$node->connect_fails(
+		"$common_connstr user=ssltestuser channel_binding=require require_auth=scram-sha-256",
+		"SCRAM with SSL, channel_binding=require, and require_auth=scram-sha-256",
+		expected_stderr =>
+		  qr/channel binding is required, but server did not offer an authentication method that supports channel binding/
+	);
+}
+
 done_testing();
-- 
2.25.1

Reply via email to