mirror of https://github.com/postgres/postgres
This commit implements OAUTHBEARER, RFC 7628, and OAuth 2.0 Device Authorization Grants, RFC 8628. In order to use this there is a new pg_hba auth method called oauth. When speaking to a OAuth- enabled server, it looks a bit like this: $ psql 'host=example.org oauth_issuer=... oauth_client_id=...' Visit https://oauth.example.org/login and enter the code: FPQ2-M4BG Device authorization is currently the only supported flow so the OAuth issuer must support that in order for users to authenticate. Third-party clients may however extend this and provide their own flows. The built-in device authorization flow is currently not supported on Windows. In order for validation to happen server side a new framework for plugging in OAuth validation modules is added. As validation is implementation specific, with no default specified in the standard, PostgreSQL does not ship with one built-in. Each pg_hba entry can specify a specific validator or be left blank for the validator installed as default. This adds a requirement on libcurl for the client side support, which is optional to build, but the server side has no additional build requirements. In order to run the tests, Python is required as this adds a https server written in Python. Tests are gated behind PG_TEST_EXTRA as they open ports. This patch has been a multi-year project with many contributors involved with reviews and in-depth discussions: Michael Paquier, Heikki Linnakangas, Zhihong Yu, Mahendrakar Srinivasarao, Andrey Chudnovsky and Stephen Frost to name a few. While Jacob Champion is the main author there have been some levels of hacking by others. Daniel Gustafsson contributed the validation module and various bits and pieces; Thomas Munro wrote the client side support for kqueue. Author: Jacob Champion <jacob.champion@enterprisedb.com> Co-authored-by: Daniel Gustafsson <daniel@yesql.se> Co-authored-by: Thomas Munro <thomas.munro@gmail.com> Reviewed-by: Daniel Gustafsson <daniel@yesql.se> Reviewed-by: Peter Eisentraut <peter@eisentraut.org> Reviewed-by: Antonin Houska <ah@cybertec.at> Reviewed-by: Kashif Zeeshan <kashi.zeeshan@gmail.com> Discussion: https://postgr.es/m/d1b467a78e0e36ed85a09adf979d04cf124a9d4b.camel@vmware.compull/200/head
parent
1fd1bd8710
commit
b3f0be788a
@ -0,0 +1,414 @@ |
||||
<!-- doc/src/sgml/oauth-validators.sgml --> |
||||
|
||||
<chapter id="oauth-validators"> |
||||
<title>OAuth Validator Modules</title> |
||||
<indexterm zone="oauth-validators"> |
||||
<primary>OAuth Validators</primary> |
||||
</indexterm> |
||||
<para> |
||||
<productname>PostgreSQL</productname> provides infrastructure for creating |
||||
custom modules to perform server-side validation of OAuth bearer tokens. |
||||
Because OAuth implementations vary so wildly, and bearer token validation is |
||||
heavily dependent on the issuing party, the server cannot check the token |
||||
itself; validator modules provide the integration layer between the server |
||||
and the OAuth provider in use. |
||||
</para> |
||||
<para> |
||||
OAuth validator modules must at least consist of an initialization function |
||||
(see <xref linkend="oauth-validator-init"/>) and the required callback for |
||||
performing validation (see <xref linkend="oauth-validator-callback-validate"/>). |
||||
</para> |
||||
<warning> |
||||
<para> |
||||
Since a misbehaving validator might let unauthorized users into the database, |
||||
correct implementation is crucial for server safety. See |
||||
<xref linkend="oauth-validator-design"/> for design considerations. |
||||
</para> |
||||
</warning> |
||||
|
||||
<sect1 id="oauth-validator-design"> |
||||
<title>Safely Designing a Validator Module</title> |
||||
<warning> |
||||
<para> |
||||
Read and understand the entirety of this section before implementing a |
||||
validator module. A malfunctioning validator is potentially worse than no |
||||
authentication at all, both because of the false sense of security it |
||||
provides, and because it may contribute to attacks against other pieces of |
||||
an OAuth ecosystem. |
||||
</para> |
||||
</warning> |
||||
|
||||
<sect2 id="oauth-validator-design-responsibilities"> |
||||
<title>Validator Responsibilities</title> |
||||
<para> |
||||
Although different modules may take very different approaches to token |
||||
validation, implementations generally need to perform three separate |
||||
actions: |
||||
</para> |
||||
<variablelist> |
||||
<varlistentry> |
||||
<term>Validate the Token</term> |
||||
<listitem> |
||||
<para> |
||||
The validator must first ensure that the presented token is in fact a |
||||
valid Bearer token for use in client authentication. The correct way to |
||||
do this depends on the provider, but it generally involves either |
||||
cryptographic operations to prove that the token was created by a trusted |
||||
party (offline validation), or the presentation of the token to that |
||||
trusted party so that it can perform validation for you (online |
||||
validation). |
||||
</para> |
||||
<para> |
||||
Online validation, usually implemented via |
||||
<ulink url="https://datatracker.ietf.org/doc/html/rfc7662">OAuth Token |
||||
Introspection</ulink>, requires fewer steps of a validator module and |
||||
allows central revocation of a token in the event that it is stolen |
||||
or misissued. However, it does require the module to make at least one |
||||
network call per authentication attempt (all of which must complete |
||||
within the configured <xref linkend="guc-authentication-timeout"/>). |
||||
Additionally, your provider may not provide introspection endpoints for |
||||
use by external resource servers. |
||||
</para> |
||||
<para> |
||||
Offline validation is much more involved, typically requiring a validator |
||||
to maintain a list of trusted signing keys for a provider and then |
||||
check the token's cryptographic signature along with its contents. |
||||
Implementations must follow the provider's instructions to the letter, |
||||
including any verification of issuer ("where is this token from?"), |
||||
audience ("who is this token for?"), and validity period ("when can this |
||||
token be used?"). Since there is no communication between the module and |
||||
the provider, tokens cannot be centrally revoked using this method; |
||||
offline validator implementations may wish to place restrictions on the |
||||
maximum length of a token's validity period. |
||||
</para> |
||||
<para> |
||||
If the token cannot be validated, the module should immediately fail. |
||||
Further authentication/authorization is pointless if the bearer token |
||||
wasn't issued by a trusted party. |
||||
</para> |
||||
</listitem> |
||||
</varlistentry> |
||||
<varlistentry> |
||||
<term>Authorize the Client</term> |
||||
<listitem> |
||||
<para> |
||||
Next the validator must ensure that the end user has given the client |
||||
permission to access the server on their behalf. This generally involves |
||||
checking the scopes that have been assigned to the token, to make sure |
||||
that they cover database access for the current HBA parameters. |
||||
</para> |
||||
<para> |
||||
The purpose of this step is to prevent an OAuth client from obtaining a |
||||
token under false pretenses. If the validator requires all tokens to |
||||
carry scopes that cover database access, the provider should then loudly |
||||
prompt the user to grant that access during the flow. This gives them the |
||||
opportunity to reject the request if the client isn't supposed to be |
||||
using their credentials to connect to databases. |
||||
</para> |
||||
<para> |
||||
While it is possible to establish client authorization without explicit |
||||
scopes by using out-of-band knowledge of the deployed architecture, doing |
||||
so removes the user from the loop, which prevents them from catching |
||||
deployment mistakes and allows any such mistakes to be exploited |
||||
silently. Access to the database must be tightly restricted to only |
||||
trusted clients |
||||
<footnote> |
||||
<para> |
||||
That is, "trusted" in the sense that the OAuth client and the |
||||
<productname>PostgreSQL</productname> server are controlled by the same |
||||
entity. Notably, the Device Authorization client flow supported by |
||||
libpq does not usually meet this bar, since it's designed for use by |
||||
public/untrusted clients. |
||||
</para> |
||||
</footnote> |
||||
if users are not prompted for additional scopes. |
||||
</para> |
||||
<para> |
||||
Even if authorization fails, a module may choose to continue to pull |
||||
authentication information from the token for use in auditing and |
||||
debugging. |
||||
</para> |
||||
</listitem> |
||||
</varlistentry> |
||||
<varlistentry> |
||||
<term>Authenticate the End User</term> |
||||
<listitem> |
||||
<para> |
||||
Finally, the validator should determine a user identifier for the token, |
||||
either by asking the provider for this information or by extracting it |
||||
from the token itself, and return that identifier to the server (which |
||||
will then make a final authorization decision using the HBA |
||||
configuration). This identifier will be available within the session via |
||||
<link linkend="functions-info-session-table"><function>system_user</function></link> |
||||
and recorded in the server logs if <xref linkend="guc-log-connections"/> |
||||
is enabled. |
||||
</para> |
||||
<para> |
||||
Different providers may record a variety of different authentication |
||||
information for an end user, typically referred to as |
||||
<emphasis>claims</emphasis>. Providers usually document which of these |
||||
claims are trustworthy enough to use for authorization decisions and |
||||
which are not. (For instance, it would probably not be wise to use an |
||||
end user's full name as the identifier for authentication, since many |
||||
providers allow users to change their display names arbitrarily.) |
||||
Ultimately, the choice of which claim (or combination of claims) to use |
||||
comes down to the provider implementation and application requirements. |
||||
</para> |
||||
<para> |
||||
Note that anonymous/pseudonymous login is possible as well, by enabling |
||||
usermap delegation; see |
||||
<xref linkend="oauth-validator-design-usermap-delegation"/>. |
||||
</para> |
||||
</listitem> |
||||
</varlistentry> |
||||
</variablelist> |
||||
</sect2> |
||||
|
||||
<sect2 id="oauth-validator-design-guidelines"> |
||||
<title>General Coding Guidelines</title> |
||||
<para> |
||||
Developers should keep the following in mind when implementing token |
||||
validation: |
||||
</para> |
||||
<variablelist> |
||||
<varlistentry> |
||||
<term>Token Confidentiality</term> |
||||
<listitem> |
||||
<para> |
||||
Modules should not write tokens, or pieces of tokens, into the server |
||||
log. This is true even if the module considers the token invalid; an |
||||
attacker who confuses a client into communicating with the wrong provider |
||||
should not be able to retrieve that (otherwise valid) token from the |
||||
disk. |
||||
</para> |
||||
<para> |
||||
Implementations that send tokens over the network (for example, to |
||||
perform online token validation with a provider) must authenticate the |
||||
peer and ensure that strong transport security is in use. |
||||
</para> |
||||
</listitem> |
||||
</varlistentry> |
||||
<varlistentry> |
||||
<term>Logging</term> |
||||
<listitem> |
||||
<para> |
||||
Modules may use the same <link linkend="error-message-reporting">logging |
||||
facilities</link> as standard extensions; however, the rules for emitting |
||||
log entries to the client are subtly different during the authentication |
||||
phase of the connection. Generally speaking, modules should log |
||||
verification problems at the <symbol>COMMERROR</symbol> level and return |
||||
normally, instead of using <symbol>ERROR</symbol>/<symbol>FATAL</symbol> |
||||
to unwind the stack, to avoid leaking information to unauthenticated |
||||
clients. |
||||
</para> |
||||
</listitem> |
||||
</varlistentry> |
||||
<varlistentry> |
||||
<term>Interruptibility</term> |
||||
<listitem> |
||||
<para> |
||||
Modules must remain interruptible by signals so that the server can |
||||
correctly handle authentication timeouts and shutdown signals from |
||||
<application>pg_ctl</application>. For example, a module receiving |
||||
<symbol>EINTR</symbol>/<symbol>EAGAIN</symbol> from a blocking call |
||||
should call <function>CHECK_FOR_INTERRUPTS()</function> before retrying. |
||||
The same should be done during any long-running loops. Failure to follow |
||||
this guidance may result in unresponsive backend sessions. |
||||
</para> |
||||
</listitem> |
||||
</varlistentry> |
||||
<varlistentry> |
||||
<term>Testing</term> |
||||
<listitem> |
||||
<para> |
||||
The breadth of testing an OAuth system is well beyond the scope of this |
||||
documentation, but at minimum, negative testing should be considered |
||||
mandatory. It's trivial to design a module that lets authorized users in; |
||||
the whole point of the system is to keep unauthorized users out. |
||||
</para> |
||||
</listitem> |
||||
</varlistentry> |
||||
<varlistentry> |
||||
<term>Documentation</term> |
||||
<listitem> |
||||
<para> |
||||
Validator implementations should document the contents and format of the |
||||
authenticated ID that is reported to the server for each end user, since |
||||
DBAs may need to use this information to construct pg_ident maps. (For |
||||
instance, is it an email address? an organizational ID number? a UUID?) |
||||
They should also document whether or not it is safe to use the module in |
||||
<symbol>delegate_ident_mapping=1</symbol> mode, and what additional |
||||
configuration is required in order to do so. |
||||
</para> |
||||
</listitem> |
||||
</varlistentry> |
||||
</variablelist> |
||||
</sect2> |
||||
|
||||
<sect2 id="oauth-validator-design-usermap-delegation"> |
||||
<title>Authorizing Users (Usermap Delegation)</title> |
||||
<para> |
||||
The standard deliverable of a validation module is the user identifier, |
||||
which the server will then compare to any configured |
||||
<link linkend="auth-username-maps"><filename>pg_ident.conf</filename> |
||||
mappings</link> and determine whether the end user is authorized to connect. |
||||
However, OAuth is itself an authorization framework, and tokens may carry |
||||
information about user privileges. For example, a token may be associated |
||||
with the organizational groups that a user belongs to, or list the roles |
||||
that a user may assume, and duplicating that knowledge into local usermaps |
||||
for every server may not be desirable. |
||||
</para> |
||||
<para> |
||||
To bypass username mapping entirely, and have the validator module assume |
||||
the additional responsibility of authorizing user connections, the HBA may |
||||
be configured with <xref linkend="auth-oauth-delegate-ident-mapping"/>. |
||||
The module may then use token scopes or an equivalent method to decide |
||||
whether the user is allowed to connect under their desired role. The user |
||||
identifier will still be recorded by the server, but it plays no part in |
||||
determining whether to continue the connection. |
||||
</para> |
||||
<para> |
||||
Using this scheme, authentication itself is optional. As long as the module |
||||
reports that the connection is authorized, login will continue even if there |
||||
is no recorded user identifier at all. This makes it possible to implement |
||||
anonymous or pseudonymous access to the database, where the third-party |
||||
provider performs all necessary authentication but does not provide any |
||||
user-identifying information to the server. (Some providers may create an |
||||
anonymized ID number that can be recorded instead, for later auditing.) |
||||
</para> |
||||
<para> |
||||
Usermap delegation provides the most architectural flexibility, but it turns |
||||
the validator module into a single point of failure for connection |
||||
authorization. Use with caution. |
||||
</para> |
||||
</sect2> |
||||
</sect1> |
||||
|
||||
<sect1 id="oauth-validator-init"> |
||||
<title>Initialization Functions</title> |
||||
<indexterm zone="oauth-validator-init"> |
||||
<primary>_PG_oauth_validator_module_init</primary> |
||||
</indexterm> |
||||
<para> |
||||
OAuth validator modules are dynamically loaded from the shared |
||||
libraries listed in <xref linkend="guc-oauth-validator-libraries"/>. |
||||
Modules are loaded on demand when requested from a login in progress. |
||||
The normal library search path is used to locate the library. To |
||||
provide the validator callbacks and to indicate that the library is an OAuth |
||||
validator module a function named |
||||
<function>_PG_oauth_validator_module_init</function> must be provided. The |
||||
return value of the function must be a pointer to a struct of type |
||||
<structname>OAuthValidatorCallbacks</structname>, which contains a magic |
||||
number and pointers to the module's token validation functions. The returned |
||||
pointer must be of server lifetime, which is typically achieved by defining |
||||
it as a <literal>static const</literal> variable in global scope. |
||||
<programlisting> |
||||
typedef struct OAuthValidatorCallbacks |
||||
{ |
||||
uint32 magic; /* must be set to PG_OAUTH_VALIDATOR_MAGIC */ |
||||
|
||||
ValidatorStartupCB startup_cb; |
||||
ValidatorShutdownCB shutdown_cb; |
||||
ValidatorValidateCB validate_cb; |
||||
} OAuthValidatorCallbacks; |
||||
|
||||
typedef const OAuthValidatorCallbacks *(*OAuthValidatorModuleInit) (void); |
||||
</programlisting> |
||||
|
||||
Only the <function>validate_cb</function> callback is required, the others |
||||
are optional. |
||||
</para> |
||||
</sect1> |
||||
|
||||
<sect1 id="oauth-validator-callbacks"> |
||||
<title>OAuth Validator Callbacks</title> |
||||
<para> |
||||
OAuth validator modules implement their functionality by defining a set of |
||||
callbacks. The server will call them as required to process the |
||||
authentication request from the user. |
||||
</para> |
||||
|
||||
<sect2 id="oauth-validator-callback-startup"> |
||||
<title>Startup Callback</title> |
||||
<para> |
||||
The <function>startup_cb</function> callback is executed directly after |
||||
loading the module. This callback can be used to set up local state and |
||||
perform additional initialization if required. If the validator module |
||||
has state it can use <structfield>state->private_data</structfield> to |
||||
store it. |
||||
|
||||
<programlisting> |
||||
typedef void (*ValidatorStartupCB) (ValidatorModuleState *state); |
||||
</programlisting> |
||||
</para> |
||||
</sect2> |
||||
|
||||
<sect2 id="oauth-validator-callback-validate"> |
||||
<title>Validate Callback</title> |
||||
<para> |
||||
The <function>validate_cb</function> callback is executed during the OAuth |
||||
exchange when a user attempts to authenticate using OAuth. Any state set in |
||||
previous calls will be available in <structfield>state->private_data</structfield>. |
||||
|
||||
<programlisting> |
||||
typedef bool (*ValidatorValidateCB) (const ValidatorModuleState *state, |
||||
const char *token, const char *role, |
||||
ValidatorModuleResult *result); |
||||
</programlisting> |
||||
|
||||
<replaceable>token</replaceable> will contain the bearer token to validate. |
||||
<application>PostgreSQL</application> has ensured that the token is well-formed syntactically, but no |
||||
other validation has been performed. <replaceable>role</replaceable> will |
||||
contain the role the user has requested to log in as. The callback must |
||||
set output parameters in the <literal>result</literal> struct, which is |
||||
defined as below: |
||||
|
||||
<programlisting> |
||||
typedef struct ValidatorModuleResult |
||||
{ |
||||
bool authorized; |
||||
char *authn_id; |
||||
} ValidatorModuleResult; |
||||
</programlisting> |
||||
|
||||
The connection will only proceed if the module sets |
||||
<structfield>result->authorized</structfield> to <literal>true</literal>. To |
||||
authenticate the user, the authenticated user name (as determined using the |
||||
token) shall be palloc'd and returned in the <structfield>result->authn_id</structfield> |
||||
field. Alternatively, <structfield>result->authn_id</structfield> may be set to |
||||
NULL if the token is valid but the associated user identity cannot be |
||||
determined. |
||||
</para> |
||||
<para> |
||||
A validator may return <literal>false</literal> to signal an internal error, |
||||
in which case any result parameters are ignored and the connection fails. |
||||
Otherwise the validator should return <literal>true</literal> to indicate |
||||
that it has processed the token and made an authorization decision. |
||||
</para> |
||||
<para> |
||||
The behavior after <function>validate_cb</function> returns depends on the |
||||
specific HBA setup. Normally, the <structfield>result->authn_id</structfield> user |
||||
name must exactly match the role that the user is logging in as. (This |
||||
behavior may be modified with a usermap.) But when authenticating against |
||||
an HBA rule with <literal>delegate_ident_mapping</literal> turned on, |
||||
<productname>PostgreSQL</productname> will not perform any checks on the value of |
||||
<structfield>result->authn_id</structfield> at all; in this case it is up to the |
||||
validator to ensure that the token carries enough privileges for the user to |
||||
log in under the indicated <replaceable>role</replaceable>. |
||||
</para> |
||||
</sect2> |
||||
|
||||
<sect2 id="oauth-validator-callback-shutdown"> |
||||
<title>Shutdown Callback</title> |
||||
<para> |
||||
The <function>shutdown_cb</function> callback is executed when the backend |
||||
process associated with the connection exits. If the validator module has |
||||
any allocated state, this callback should free it to avoid resource leaks. |
||||
<programlisting> |
||||
typedef void (*ValidatorShutdownCB) (ValidatorModuleState *state); |
||||
</programlisting> |
||||
</para> |
||||
</sect2> |
||||
|
||||
</sect1> |
||||
</chapter> |
@ -0,0 +1,894 @@ |
||||
/*-------------------------------------------------------------------------
|
||||
* |
||||
* auth-oauth.c |
||||
* Server-side implementation of the SASL OAUTHBEARER mechanism. |
||||
* |
||||
* See the following RFC for more details: |
||||
* - RFC 7628: https://datatracker.ietf.org/doc/html/rfc7628
|
||||
* |
||||
* Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group |
||||
* Portions Copyright (c) 1994, Regents of the University of California |
||||
* |
||||
* src/backend/libpq/auth-oauth.c |
||||
* |
||||
*------------------------------------------------------------------------- |
||||
*/ |
||||
#include "postgres.h" |
||||
|
||||
#include <unistd.h> |
||||
#include <fcntl.h> |
||||
|
||||
#include "common/oauth-common.h" |
||||
#include "fmgr.h" |
||||
#include "lib/stringinfo.h" |
||||
#include "libpq/auth.h" |
||||
#include "libpq/hba.h" |
||||
#include "libpq/oauth.h" |
||||
#include "libpq/sasl.h" |
||||
#include "storage/fd.h" |
||||
#include "storage/ipc.h" |
||||
#include "utils/json.h" |
||||
#include "utils/varlena.h" |
||||
|
||||
/* GUC */ |
||||
char *oauth_validator_libraries_string = NULL; |
||||
|
||||
static void oauth_get_mechanisms(Port *port, StringInfo buf); |
||||
static void *oauth_init(Port *port, const char *selected_mech, const char *shadow_pass); |
||||
static int oauth_exchange(void *opaq, const char *input, int inputlen, |
||||
char **output, int *outputlen, const char **logdetail); |
||||
|
||||
static void load_validator_library(const char *libname); |
||||
static void shutdown_validator_library(void *arg); |
||||
|
||||
static ValidatorModuleState *validator_module_state; |
||||
static const OAuthValidatorCallbacks *ValidatorCallbacks; |
||||
|
||||
/* Mechanism declaration */ |
||||
const pg_be_sasl_mech pg_be_oauth_mech = { |
||||
.get_mechanisms = oauth_get_mechanisms, |
||||
.init = oauth_init, |
||||
.exchange = oauth_exchange, |
||||
|
||||
.max_message_length = PG_MAX_AUTH_TOKEN_LENGTH, |
||||
}; |
||||
|
||||
/* Valid states for the oauth_exchange() machine. */ |
||||
enum oauth_state |
||||
{ |
||||
OAUTH_STATE_INIT = 0, |
||||
OAUTH_STATE_ERROR, |
||||
OAUTH_STATE_FINISHED, |
||||
}; |
||||
|
||||
/* Mechanism callback state. */ |
||||
struct oauth_ctx |
||||
{ |
||||
enum oauth_state state; |
||||
Port *port; |
||||
const char *issuer; |
||||
const char *scope; |
||||
}; |
||||
|
||||
static char *sanitize_char(char c); |
||||
static char *parse_kvpairs_for_auth(char **input); |
||||
static void generate_error_response(struct oauth_ctx *ctx, char **output, int *outputlen); |
||||
static bool validate(Port *port, const char *auth); |
||||
|
||||
/* Constants seen in an OAUTHBEARER client initial response. */ |
||||
#define KVSEP 0x01 /* separator byte for key/value pairs */ |
||||
#define AUTH_KEY "auth" /* key containing the Authorization header */ |
||||
#define BEARER_SCHEME "Bearer " /* required header scheme (case-insensitive!) */ |
||||
|
||||
/*
|
||||
* Retrieves the OAUTHBEARER mechanism list (currently a single item). |
||||
* |
||||
* For a full description of the API, see libpq/sasl.h. |
||||
*/ |
||||
static void |
||||
oauth_get_mechanisms(Port *port, StringInfo buf) |
||||
{ |
||||
/* Only OAUTHBEARER is supported. */ |
||||
appendStringInfoString(buf, OAUTHBEARER_NAME); |
||||
appendStringInfoChar(buf, '\0'); |
||||
} |
||||
|
||||
/*
|
||||
* Initializes mechanism state and loads the configured validator module. |
||||
* |
||||
* For a full description of the API, see libpq/sasl.h. |
||||
*/ |
||||
static void * |
||||
oauth_init(Port *port, const char *selected_mech, const char *shadow_pass) |
||||
{ |
||||
struct oauth_ctx *ctx; |
||||
|
||||
if (strcmp(selected_mech, OAUTHBEARER_NAME) != 0) |
||||
ereport(ERROR, |
||||
errcode(ERRCODE_PROTOCOL_VIOLATION), |
||||
errmsg("client selected an invalid SASL authentication mechanism")); |
||||
|
||||
ctx = palloc0(sizeof(*ctx)); |
||||
|
||||
ctx->state = OAUTH_STATE_INIT; |
||||
ctx->port = port; |
||||
|
||||
Assert(port->hba); |
||||
ctx->issuer = port->hba->oauth_issuer; |
||||
ctx->scope = port->hba->oauth_scope; |
||||
|
||||
load_validator_library(port->hba->oauth_validator); |
||||
|
||||
return ctx; |
||||
} |
||||
|
||||
/*
|
||||
* Implements the OAUTHBEARER SASL exchange (RFC 7628, Sec. 3.2). This pulls |
||||
* apart the client initial response and validates the Bearer token. It also |
||||
* handles the dummy error response for a failed handshake, as described in |
||||
* Sec. 3.2.3. |
||||
* |
||||
* For a full description of the API, see libpq/sasl.h. |
||||
*/ |
||||
static int |
||||
oauth_exchange(void *opaq, const char *input, int inputlen, |
||||
char **output, int *outputlen, const char **logdetail) |
||||
{ |
||||
char *input_copy; |
||||
char *p; |
||||
char cbind_flag; |
||||
char *auth; |
||||
int status; |
||||
|
||||
struct oauth_ctx *ctx = opaq; |
||||
|
||||
*output = NULL; |
||||
*outputlen = -1; |
||||
|
||||
/*
|
||||
* If the client didn't include an "Initial Client Response" in the |
||||
* SASLInitialResponse message, send an empty challenge, to which the |
||||
* client will respond with the same data that usually comes in the |
||||
* Initial Client Response. |
||||
*/ |
||||
if (input == NULL) |
||||
{ |
||||
Assert(ctx->state == OAUTH_STATE_INIT); |
||||
|
||||
*output = pstrdup(""); |
||||
*outputlen = 0; |
||||
return PG_SASL_EXCHANGE_CONTINUE; |
||||
} |
||||
|
||||
/*
|
||||
* Check that the input length agrees with the string length of the input. |
||||
*/ |
||||
if (inputlen == 0) |
||||
ereport(ERROR, |
||||
errcode(ERRCODE_PROTOCOL_VIOLATION), |
||||
errmsg("malformed OAUTHBEARER message"), |
||||
errdetail("The message is empty.")); |
||||
if (inputlen != strlen(input)) |
||||
ereport(ERROR, |
||||
errcode(ERRCODE_PROTOCOL_VIOLATION), |
||||
errmsg("malformed OAUTHBEARER message"), |
||||
errdetail("Message length does not match input length.")); |
||||
|
||||
switch (ctx->state) |
||||
{ |
||||
case OAUTH_STATE_INIT: |
||||
/* Handle this case below. */ |
||||
break; |
||||
|
||||
case OAUTH_STATE_ERROR: |
||||
|
||||
/*
|
||||
* Only one response is valid for the client during authentication |
||||
* failure: a single kvsep. |
||||
*/ |
||||
if (inputlen != 1 || *input != KVSEP) |
||||
ereport(ERROR, |
||||
errcode(ERRCODE_PROTOCOL_VIOLATION), |
||||
errmsg("malformed OAUTHBEARER message"), |
||||
errdetail("Client did not send a kvsep response.")); |
||||
|
||||
/* The (failed) handshake is now complete. */ |
||||
ctx->state = OAUTH_STATE_FINISHED; |
||||
return PG_SASL_EXCHANGE_FAILURE; |
||||
|
||||
default: |
||||
elog(ERROR, "invalid OAUTHBEARER exchange state"); |
||||
return PG_SASL_EXCHANGE_FAILURE; |
||||
} |
||||
|
||||
/* Handle the client's initial message. */ |
||||
p = input_copy = pstrdup(input); |
||||
|
||||
/*
|
||||
* OAUTHBEARER does not currently define a channel binding (so there is no |
||||
* OAUTHBEARER-PLUS, and we do not accept a 'p' specifier). We accept a |
||||
* 'y' specifier purely for the remote chance that a future specification |
||||
* could define one; then future clients can still interoperate with this |
||||
* server implementation. 'n' is the expected case. |
||||
*/ |
||||
cbind_flag = *p; |
||||
switch (cbind_flag) |
||||
{ |
||||
case 'p': |
||||
ereport(ERROR, |
||||
errcode(ERRCODE_PROTOCOL_VIOLATION), |
||||
errmsg("malformed OAUTHBEARER message"), |
||||
errdetail("The server does not support channel binding for OAuth, but the client message includes channel binding data.")); |
||||
break; |
||||
|
||||
case 'y': /* fall through */ |
||||
case 'n': |
||||
p++; |
||||
if (*p != ',') |
||||
ereport(ERROR, |
||||
errcode(ERRCODE_PROTOCOL_VIOLATION), |
||||
errmsg("malformed OAUTHBEARER message"), |
||||
errdetail("Comma expected, but found character \"%s\".", |
||||
sanitize_char(*p))); |
||||
p++; |
||||
break; |
||||
|
||||
default: |
||||
ereport(ERROR, |
||||
errcode(ERRCODE_PROTOCOL_VIOLATION), |
||||
errmsg("malformed OAUTHBEARER message"), |
||||
errdetail("Unexpected channel-binding flag \"%s\".", |
||||
sanitize_char(cbind_flag))); |
||||
} |
||||
|
||||
/*
|
||||
* Forbid optional authzid (authorization identity). We don't support it. |
||||
*/ |
||||
if (*p == 'a') |
||||
ereport(ERROR, |
||||
errcode(ERRCODE_FEATURE_NOT_SUPPORTED), |
||||
errmsg("client uses authorization identity, but it is not supported")); |
||||
if (*p != ',') |
||||
ereport(ERROR, |
||||
errcode(ERRCODE_PROTOCOL_VIOLATION), |
||||
errmsg("malformed OAUTHBEARER message"), |
||||
errdetail("Unexpected attribute \"%s\" in client-first-message.", |
||||
sanitize_char(*p))); |
||||
p++; |
||||
|
||||
/* All remaining fields are separated by the RFC's kvsep (\x01). */ |
||||
if (*p != KVSEP) |
||||
ereport(ERROR, |
||||
errcode(ERRCODE_PROTOCOL_VIOLATION), |
||||
errmsg("malformed OAUTHBEARER message"), |
||||
errdetail("Key-value separator expected, but found character \"%s\".", |
||||
sanitize_char(*p))); |
||||
p++; |
||||
|
||||
auth = parse_kvpairs_for_auth(&p); |
||||
if (!auth) |
||||
ereport(ERROR, |
||||
errcode(ERRCODE_PROTOCOL_VIOLATION), |
||||
errmsg("malformed OAUTHBEARER message"), |
||||
errdetail("Message does not contain an auth value.")); |
||||
|
||||
/* We should be at the end of our message. */ |
||||
if (*p) |
||||
ereport(ERROR, |
||||
errcode(ERRCODE_PROTOCOL_VIOLATION), |
||||
errmsg("malformed OAUTHBEARER message"), |
||||
errdetail("Message contains additional data after the final terminator.")); |
||||
|
||||
if (!validate(ctx->port, auth)) |
||||
{ |
||||
generate_error_response(ctx, output, outputlen); |
||||
|
||||
ctx->state = OAUTH_STATE_ERROR; |
||||
status = PG_SASL_EXCHANGE_CONTINUE; |
||||
} |
||||
else |
||||
{ |
||||
ctx->state = OAUTH_STATE_FINISHED; |
||||
status = PG_SASL_EXCHANGE_SUCCESS; |
||||
} |
||||
|
||||
/* Don't let extra copies of the bearer token hang around. */ |
||||
explicit_bzero(input_copy, inputlen); |
||||
|
||||
return status; |
||||
} |
||||
|
||||
/*
|
||||
* Convert an arbitrary byte to printable form. For error messages. |
||||
* |
||||
* If it's a printable ASCII character, print it as a single character. |
||||
* otherwise, print it in hex. |
||||
* |
||||
* The returned pointer points to a static buffer. |
||||
*/ |
||||
static char * |
||||
sanitize_char(char c) |
||||
{ |
||||
static char buf[5]; |
||||
|
||||
if (c >= 0x21 && c <= 0x7E) |
||||
snprintf(buf, sizeof(buf), "'%c'", c); |
||||
else |
||||
snprintf(buf, sizeof(buf), "0x%02x", (unsigned char) c); |
||||
return buf; |
||||
} |
||||
|
||||
/*
|
||||
* Performs syntactic validation of a key and value from the initial client |
||||
* response. (Semantic validation of interesting values must be performed |
||||
* later.) |
||||
*/ |
||||
static void |
||||
validate_kvpair(const char *key, const char *val) |
||||
{ |
||||
/*-----
|
||||
* From Sec 3.1: |
||||
* key = 1*(ALPHA) |
||||
*/ |
||||
static const char *key_allowed_set = |
||||
"abcdefghijklmnopqrstuvwxyz" |
||||
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"; |
||||
|
||||
size_t span; |
||||
|
||||
if (!key[0]) |
||||
ereport(ERROR, |
||||
errcode(ERRCODE_PROTOCOL_VIOLATION), |
||||
errmsg("malformed OAUTHBEARER message"), |
||||
errdetail("Message contains an empty key name.")); |
||||
|
||||
span = strspn(key, key_allowed_set); |
||||
if (key[span] != '\0') |
||||
ereport(ERROR, |
||||
errcode(ERRCODE_PROTOCOL_VIOLATION), |
||||
errmsg("malformed OAUTHBEARER message"), |
||||
errdetail("Message contains an invalid key name.")); |
||||
|
||||
/*-----
|
||||
* From Sec 3.1: |
||||
* value = *(VCHAR / SP / HTAB / CR / LF ) |
||||
* |
||||
* The VCHAR (visible character) class is large; a loop is more |
||||
* straightforward than strspn(). |
||||
*/ |
||||
for (; *val; ++val) |
||||
{ |
||||
if (0x21 <= *val && *val <= 0x7E) |
||||
continue; /* VCHAR */ |
||||
|
||||
switch (*val) |
||||
{ |
||||
case ' ': |
||||
case '\t': |
||||
case '\r': |
||||
case '\n': |
||||
continue; /* SP, HTAB, CR, LF */ |
||||
|
||||
default: |
||||
ereport(ERROR, |
||||
errcode(ERRCODE_PROTOCOL_VIOLATION), |
||||
errmsg("malformed OAUTHBEARER message"), |
||||
errdetail("Message contains an invalid value.")); |
||||
} |
||||
} |
||||
} |
||||
|
||||
/*
|
||||
* Consumes all kvpairs in an OAUTHBEARER exchange message. If the "auth" key is |
||||
* found, its value is returned. |
||||
*/ |
||||
static char * |
||||
parse_kvpairs_for_auth(char **input) |
||||
{ |
||||
char *pos = *input; |
||||
char *auth = NULL; |
||||
|
||||
/*----
|
||||
* The relevant ABNF, from Sec. 3.1: |
||||
* |
||||
* kvsep = %x01 |
||||
* key = 1*(ALPHA) |
||||
* value = *(VCHAR / SP / HTAB / CR / LF ) |
||||
* kvpair = key "=" value kvsep |
||||
* ;;gs2-header = See RFC 5801 |
||||
* client-resp = (gs2-header kvsep *kvpair kvsep) / kvsep |
||||
* |
||||
* By the time we reach this code, the gs2-header and initial kvsep have |
||||
* already been validated. We start at the beginning of the first kvpair. |
||||
*/ |
||||
|
||||
while (*pos) |
||||
{ |
||||
char *end; |
||||
char *sep; |
||||
char *key; |
||||
char *value; |
||||
|
||||
/*
|
||||
* Find the end of this kvpair. Note that input is null-terminated by |
||||
* the SASL code, so the strchr() is bounded. |
||||
*/ |
||||
end = strchr(pos, KVSEP); |
||||
if (!end) |
||||
ereport(ERROR, |
||||
errcode(ERRCODE_PROTOCOL_VIOLATION), |
||||
errmsg("malformed OAUTHBEARER message"), |
||||
errdetail("Message contains an unterminated key/value pair.")); |
||||
*end = '\0'; |
||||
|
||||
if (pos == end) |
||||
{ |
||||
/* Empty kvpair, signifying the end of the list. */ |
||||
*input = pos + 1; |
||||
return auth; |
||||
} |
||||
|
||||
/*
|
||||
* Find the end of the key name. |
||||
*/ |
||||
sep = strchr(pos, '='); |
||||
if (!sep) |
||||
ereport(ERROR, |
||||
errcode(ERRCODE_PROTOCOL_VIOLATION), |
||||
errmsg("malformed OAUTHBEARER message"), |
||||
errdetail("Message contains a key without a value.")); |
||||
*sep = '\0'; |
||||
|
||||
/* Both key and value are now safely terminated. */ |
||||
key = pos; |
||||
value = sep + 1; |
||||
validate_kvpair(key, value); |
||||
|
||||
if (strcmp(key, AUTH_KEY) == 0) |
||||
{ |
||||
if (auth) |
||||
ereport(ERROR, |
||||
errcode(ERRCODE_PROTOCOL_VIOLATION), |
||||
errmsg("malformed OAUTHBEARER message"), |
||||
errdetail("Message contains multiple auth values.")); |
||||
|
||||
auth = value; |
||||
} |
||||
else |
||||
{ |
||||
/*
|
||||
* The RFC also defines the host and port keys, but they are not |
||||
* required for OAUTHBEARER and we do not use them. Also, per Sec. |
||||
* 3.1, any key/value pairs we don't recognize must be ignored. |
||||
*/ |
||||
} |
||||
|
||||
/* Move to the next pair. */ |
||||
pos = end + 1; |
||||
} |
||||
|
||||
ereport(ERROR, |
||||
errcode(ERRCODE_PROTOCOL_VIOLATION), |
||||
errmsg("malformed OAUTHBEARER message"), |
||||
errdetail("Message did not contain a final terminator.")); |
||||
|
||||
pg_unreachable(); |
||||
return NULL; |
||||
} |
||||
|
||||
/*
|
||||
* Builds the JSON response for failed authentication (RFC 7628, Sec. 3.2.2). |
||||
* This contains the required scopes for entry and a pointer to the OAuth/OpenID |
||||
* discovery document, which the client may use to conduct its OAuth flow. |
||||
*/ |
||||
static void |
||||
generate_error_response(struct oauth_ctx *ctx, char **output, int *outputlen) |
||||
{ |
||||
StringInfoData buf; |
||||
StringInfoData issuer; |
||||
|
||||
/*
|
||||
* The admin needs to set an issuer and scope for OAuth to work. There's |
||||
* not really a way to hide this from the user, either, because we can't |
||||
* choose a "default" issuer, so be honest in the failure message. (In |
||||
* practice such configurations are rejected during HBA parsing.) |
||||
*/ |
||||
if (!ctx->issuer || !ctx->scope) |
||||
ereport(FATAL, |
||||
errcode(ERRCODE_INTERNAL_ERROR), |
||||
errmsg("OAuth is not properly configured for this user"), |
||||
errdetail_log("The issuer and scope parameters must be set in pg_hba.conf.")); |
||||
|
||||
/*
|
||||
* Build a default .well-known URI based on our issuer, unless the HBA has |
||||
* already provided one. |
||||
*/ |
||||
initStringInfo(&issuer); |
||||
appendStringInfoString(&issuer, ctx->issuer); |
||||
if (strstr(ctx->issuer, "/.well-known/") == NULL) |
||||
appendStringInfoString(&issuer, "/.well-known/openid-configuration"); |
||||
|
||||
initStringInfo(&buf); |
||||
|
||||
/*
|
||||
* Escaping the string here is belt-and-suspenders defensive programming |
||||
* since escapable characters aren't valid in either the issuer URI or the |
||||
* scope list, but the HBA doesn't enforce that yet. |
||||
*/ |
||||
appendStringInfoString(&buf, "{ \"status\": \"invalid_token\", "); |
||||
|
||||
appendStringInfoString(&buf, "\"openid-configuration\": "); |
||||
escape_json(&buf, issuer.data); |
||||
pfree(issuer.data); |
||||
|
||||
appendStringInfoString(&buf, ", \"scope\": "); |
||||
escape_json(&buf, ctx->scope); |
||||
|
||||
appendStringInfoString(&buf, " }"); |
||||
|
||||
*output = buf.data; |
||||
*outputlen = buf.len; |
||||
} |
||||
|
||||
/*-----
|
||||
* Validates the provided Authorization header and returns the token from |
||||
* within it. NULL is returned on validation failure. |
||||
* |
||||
* Only Bearer tokens are accepted. The ABNF is defined in RFC 6750, Sec. |
||||
* 2.1: |
||||
* |
||||
* b64token = 1*( ALPHA / DIGIT / |
||||
* "-" / "." / "_" / "~" / "+" / "/" ) *"=" |
||||
* credentials = "Bearer" 1*SP b64token |
||||
* |
||||
* The "credentials" construction is what we receive in our auth value. |
||||
* |
||||
* Since that spec is subordinate to HTTP (i.e. the HTTP Authorization |
||||
* header format; RFC 9110 Sec. 11), the "Bearer" scheme string must be |
||||
* compared case-insensitively. (This is not mentioned in RFC 6750, but the |
||||
* OAUTHBEARER spec points it out: RFC 7628 Sec. 4.) |
||||
* |
||||
* Invalid formats are technically a protocol violation, but we shouldn't |
||||
* reflect any information about the sensitive Bearer token back to the |
||||
* client; log at COMMERROR instead. |
||||
*/ |
||||
static const char * |
||||
validate_token_format(const char *header) |
||||
{ |
||||
size_t span; |
||||
const char *token; |
||||
static const char *const b64token_allowed_set = |
||||
"abcdefghijklmnopqrstuvwxyz" |
||||
"ABCDEFGHIJKLMNOPQRSTUVWXYZ" |
||||
"0123456789-._~+/"; |
||||
|
||||
/* Missing auth headers should be handled by the caller. */ |
||||
Assert(header); |
||||
|
||||
if (header[0] == '\0') |
||||
{ |
||||
/*
|
||||
* A completely empty auth header represents a query for |
||||
* authentication parameters. The client expects it to fail; there's |
||||
* no need to make any extra noise in the logs. |
||||
* |
||||
* TODO: should we find a way to return STATUS_EOF at the top level, |
||||
* to suppress the authentication error entirely? |
||||
*/ |
||||
return NULL; |
||||
} |
||||
|
||||
if (pg_strncasecmp(header, BEARER_SCHEME, strlen(BEARER_SCHEME))) |
||||
{ |
||||
ereport(COMMERROR, |
||||
errcode(ERRCODE_PROTOCOL_VIOLATION), |
||||
errmsg("malformed OAuth bearer token"), |
||||
errdetail_log("Client response indicated a non-Bearer authentication scheme.")); |
||||
return NULL; |
||||
} |
||||
|
||||
/* Pull the bearer token out of the auth value. */ |
||||
token = header + strlen(BEARER_SCHEME); |
||||
|
||||
/* Swallow any additional spaces. */ |
||||
while (*token == ' ') |
||||
token++; |
||||
|
||||
/* Tokens must not be empty. */ |
||||
if (!*token) |
||||
{ |
||||
ereport(COMMERROR, |
||||
errcode(ERRCODE_PROTOCOL_VIOLATION), |
||||
errmsg("malformed OAuth bearer token"), |
||||
errdetail_log("Bearer token is empty.")); |
||||
return NULL; |
||||
} |
||||
|
||||
/*
|
||||
* Make sure the token contains only allowed characters. Tokens may end |
||||
* with any number of '=' characters. |
||||
*/ |
||||
span = strspn(token, b64token_allowed_set); |
||||
while (token[span] == '=') |
||||
span++; |
||||
|
||||
if (token[span] != '\0') |
||||
{ |
||||
/*
|
||||
* This error message could be more helpful by printing the |
||||
* problematic character(s), but that'd be a bit like printing a piece |
||||
* of someone's password into the logs. |
||||
*/ |
||||
ereport(COMMERROR, |
||||
errcode(ERRCODE_PROTOCOL_VIOLATION), |
||||
errmsg("malformed OAuth bearer token"), |
||||
errdetail_log("Bearer token is not in the correct format.")); |
||||
return NULL; |
||||
} |
||||
|
||||
return token; |
||||
} |
||||
|
||||
/*
|
||||
* Checks that the "auth" kvpair in the client response contains a syntactically |
||||
* valid Bearer token, then passes it along to the loaded validator module for |
||||
* authorization. Returns true if validation succeeds. |
||||
*/ |
||||
static bool |
||||
validate(Port *port, const char *auth) |
||||
{ |
||||
int map_status; |
||||
ValidatorModuleResult *ret; |
||||
const char *token; |
||||
bool status; |
||||
|
||||
/* Ensure that we have a correct token to validate */ |
||||
if (!(token = validate_token_format(auth))) |
||||
return false; |
||||
|
||||
/*
|
||||
* Ensure that we have a validation library loaded, this should always be |
||||
* the case and an error here is indicative of a bug. |
||||
*/ |
||||
if (!ValidatorCallbacks || !ValidatorCallbacks->validate_cb) |
||||
ereport(FATAL, |
||||
errcode(ERRCODE_INTERNAL_ERROR), |
||||
errmsg("validation of OAuth token requested without a validator loaded")); |
||||
|
||||
/* Call the validation function from the validator module */ |
||||
ret = palloc0(sizeof(ValidatorModuleResult)); |
||||
if (!ValidatorCallbacks->validate_cb(validator_module_state, token, |
||||
port->user_name, ret)) |
||||
{ |
||||
ereport(WARNING, |
||||
errcode(ERRCODE_INTERNAL_ERROR), |
||||
errmsg("internal error in OAuth validator module")); |
||||
return false; |
||||
} |
||||
|
||||
/*
|
||||
* Log any authentication results even if the token isn't authorized; it |
||||
* might be useful for auditing or troubleshooting. |
||||
*/ |
||||
if (ret->authn_id) |
||||
set_authn_id(port, ret->authn_id); |
||||
|
||||
if (!ret->authorized) |
||||
{ |
||||
ereport(LOG, |
||||
errmsg("OAuth bearer authentication failed for user \"%s\"", |
||||
port->user_name), |
||||
errdetail_log("Validator failed to authorize the provided token.")); |
||||
|
||||
status = false; |
||||
goto cleanup; |
||||
} |
||||
|
||||
if (port->hba->oauth_skip_usermap) |
||||
{ |
||||
/*
|
||||
* If the validator is our authorization authority, we're done. |
||||
* Authentication may or may not have been performed depending on the |
||||
* validator implementation; all that matters is that the validator |
||||
* says the user can log in with the target role. |
||||
*/ |
||||
status = true; |
||||
goto cleanup; |
||||
} |
||||
|
||||
/* Make sure the validator authenticated the user. */ |
||||
if (ret->authn_id == NULL || ret->authn_id[0] == '\0') |
||||
{ |
||||
ereport(LOG, |
||||
errmsg("OAuth bearer authentication failed for user \"%s\"", |
||||
port->user_name), |
||||
errdetail_log("Validator provided no identity.")); |
||||
|
||||
status = false; |
||||
goto cleanup; |
||||
} |
||||
|
||||
/* Finally, check the user map. */ |
||||
map_status = check_usermap(port->hba->usermap, port->user_name, |
||||
MyClientConnectionInfo.authn_id, false); |
||||
status = (map_status == STATUS_OK); |
||||
|
||||
cleanup: |
||||
|
||||
/*
|
||||
* Clear and free the validation result from the validator module once |
||||
* we're done with it. |
||||
*/ |
||||
if (ret->authn_id != NULL) |
||||
pfree(ret->authn_id); |
||||
pfree(ret); |
||||
|
||||
return status; |
||||
} |
||||
|
||||
/*
|
||||
* load_validator_library |
||||
* |
||||
* Load the configured validator library in order to perform token validation. |
||||
* There is no built-in fallback since validation is implementation specific. If |
||||
* no validator library is configured, or if it fails to load, then error out |
||||
* since token validation won't be possible. |
||||
*/ |
||||
static void |
||||
load_validator_library(const char *libname) |
||||
{ |
||||
OAuthValidatorModuleInit validator_init; |
||||
MemoryContextCallback *mcb; |
||||
|
||||
/*
|
||||
* The presence, and validity, of libname has already been established by |
||||
* check_oauth_validator so we don't need to perform more than Assert |
||||
* level checking here. |
||||
*/ |
||||
Assert(libname && *libname); |
||||
|
||||
validator_init = (OAuthValidatorModuleInit) |
||||
load_external_function(libname, "_PG_oauth_validator_module_init", |
||||
false, NULL); |
||||
|
||||
/*
|
||||
* The validator init function is required since it will set the callbacks |
||||
* for the validator library. |
||||
*/ |
||||
if (validator_init == NULL) |
||||
ereport(ERROR, |
||||
errmsg("%s module \"%s\" must define the symbol %s", |
||||
"OAuth validator", libname, "_PG_oauth_validator_module_init")); |
||||
|
||||
ValidatorCallbacks = (*validator_init) (); |
||||
Assert(ValidatorCallbacks); |
||||
|
||||
/*
|
||||
* Check the magic number, to protect against break-glass scenarios where |
||||
* the ABI must change within a major version. load_external_function() |
||||
* already checks for compatibility across major versions. |
||||
*/ |
||||
if (ValidatorCallbacks->magic != PG_OAUTH_VALIDATOR_MAGIC) |
||||
ereport(ERROR, |
||||
errmsg("%s module \"%s\": magic number mismatch", |
||||
"OAuth validator", libname), |
||||
errdetail("Server has magic number 0x%08X, module has 0x%08X.", |
||||
PG_OAUTH_VALIDATOR_MAGIC, ValidatorCallbacks->magic)); |
||||
|
||||
/*
|
||||
* Make sure all required callbacks are present in the ValidatorCallbacks |
||||
* structure. Right now only the validation callback is required. |
||||
*/ |
||||
if (ValidatorCallbacks->validate_cb == NULL) |
||||
ereport(ERROR, |
||||
errmsg("%s module \"%s\" must provide a %s callback", |
||||
"OAuth validator", libname, "validate_cb")); |
||||
|
||||
/* Allocate memory for validator library private state data */ |
||||
validator_module_state = (ValidatorModuleState *) palloc0(sizeof(ValidatorModuleState)); |
||||
validator_module_state->sversion = PG_VERSION_NUM; |
||||
|
||||
if (ValidatorCallbacks->startup_cb != NULL) |
||||
ValidatorCallbacks->startup_cb(validator_module_state); |
||||
|
||||
/* Shut down the library before cleaning up its state. */ |
||||
mcb = palloc0(sizeof(*mcb)); |
||||
mcb->func = shutdown_validator_library; |
||||
|
||||
MemoryContextRegisterResetCallback(CurrentMemoryContext, mcb); |
||||
} |
||||
|
||||
/*
|
||||
* Call the validator module's shutdown callback, if one is provided. This is |
||||
* invoked during memory context reset. |
||||
*/ |
||||
static void |
||||
shutdown_validator_library(void *arg) |
||||
{ |
||||
if (ValidatorCallbacks->shutdown_cb != NULL) |
||||
ValidatorCallbacks->shutdown_cb(validator_module_state); |
||||
} |
||||
|
||||
/*
|
||||
* Ensure an OAuth validator named in the HBA is permitted by the configuration. |
||||
* |
||||
* If the validator is currently unset and exactly one library is declared in |
||||
* oauth_validator_libraries, then that library will be used as the validator. |
||||
* Otherwise the name must be present in the list of oauth_validator_libraries. |
||||
*/ |
||||
bool |
||||
check_oauth_validator(HbaLine *hbaline, int elevel, char **err_msg) |
||||
{ |
||||
int line_num = hbaline->linenumber; |
||||
const char *file_name = hbaline->sourcefile; |
||||
char *rawstring; |
||||
List *elemlist = NIL; |
||||
|
||||
*err_msg = NULL; |
||||
|
||||
if (oauth_validator_libraries_string[0] == '\0') |
||||
{ |
||||
ereport(elevel, |
||||
errcode(ERRCODE_CONFIG_FILE_ERROR), |
||||
errmsg("oauth_validator_libraries must be set for authentication method %s", |
||||
"oauth"), |
||||
errcontext("line %d of configuration file \"%s\"", |
||||
line_num, file_name)); |
||||
*err_msg = psprintf("oauth_validator_libraries must be set for authentication method %s", |
||||
"oauth"); |
||||
return false; |
||||
} |
||||
|
||||
/* SplitDirectoriesString needs a modifiable copy */ |
||||
rawstring = pstrdup(oauth_validator_libraries_string); |
||||
|
||||
if (!SplitDirectoriesString(rawstring, ',', &elemlist)) |
||||
{ |
||||
/* syntax error in list */ |
||||
ereport(elevel, |
||||
errcode(ERRCODE_CONFIG_FILE_ERROR), |
||||
errmsg("invalid list syntax in parameter \"%s\"", |
||||
"oauth_validator_libraries")); |
||||
*err_msg = psprintf("invalid list syntax in parameter \"%s\"", |
||||
"oauth_validator_libraries"); |
||||
goto done; |
||||
} |
||||
|
||||
if (!hbaline->oauth_validator) |
||||
{ |
||||
if (elemlist->length == 1) |
||||
{ |
||||
hbaline->oauth_validator = pstrdup(linitial(elemlist)); |
||||
goto done; |
||||
} |
||||
|
||||
ereport(elevel, |
||||
errcode(ERRCODE_CONFIG_FILE_ERROR), |
||||
errmsg("authentication method \"oauth\" requires argument \"validator\" to be set when oauth_validator_libraries contains multiple options"), |
||||
errcontext("line %d of configuration file \"%s\"", |
||||
line_num, file_name)); |
||||
*err_msg = "authentication method \"oauth\" requires argument \"validator\" to be set when oauth_validator_libraries contains multiple options"; |
||||
goto done; |
||||
} |
||||
|
||||
foreach_ptr(char, allowed, elemlist) |
||||
{ |
||||
if (strcmp(allowed, hbaline->oauth_validator) == 0) |
||||
goto done; |
||||
} |
||||
|
||||
ereport(elevel, |
||||
errcode(ERRCODE_INVALID_PARAMETER_VALUE), |
||||
errmsg("validator \"%s\" is not permitted by %s", |
||||
hbaline->oauth_validator, "oauth_validator_libraries"), |
||||
errcontext("line %d of configuration file \"%s\"", |
||||
line_num, file_name)); |
||||
*err_msg = psprintf("validator \"%s\" is not permitted by %s", |
||||
hbaline->oauth_validator, "oauth_validator_libraries"); |
||||
|
||||
done: |
||||
list_free_deep(elemlist); |
||||
pfree(rawstring); |
||||
|
||||
return (*err_msg == NULL); |
||||
} |
@ -0,0 +1,19 @@ |
||||
/*-------------------------------------------------------------------------
|
||||
* |
||||
* oauth-common.h |
||||
* Declarations for helper functions used for OAuth/OIDC authentication |
||||
* |
||||
* Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group |
||||
* Portions Copyright (c) 1994, Regents of the University of California |
||||
* |
||||
* src/include/common/oauth-common.h |
||||
* |
||||
*------------------------------------------------------------------------- |
||||
*/ |
||||
#ifndef OAUTH_COMMON_H |
||||
#define OAUTH_COMMON_H |
||||
|
||||
/* Name of SASL mechanism per IANA */ |
||||
#define OAUTHBEARER_NAME "OAUTHBEARER" |
||||
|
||||
#endif /* OAUTH_COMMON_H */ |
@ -0,0 +1,101 @@ |
||||
/*-------------------------------------------------------------------------
|
||||
* |
||||
* oauth.h |
||||
* Interface to libpq/auth-oauth.c |
||||
* |
||||
* Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group |
||||
* Portions Copyright (c) 1994, Regents of the University of California |
||||
* |
||||
* src/include/libpq/oauth.h |
||||
* |
||||
*------------------------------------------------------------------------- |
||||
*/ |
||||
#ifndef PG_OAUTH_H |
||||
#define PG_OAUTH_H |
||||
|
||||
#include "libpq/libpq-be.h" |
||||
#include "libpq/sasl.h" |
||||
|
||||
extern PGDLLIMPORT char *oauth_validator_libraries_string; |
||||
|
||||
typedef struct ValidatorModuleState |
||||
{ |
||||
/* Holds the server's PG_VERSION_NUM. Reserved for future extensibility. */ |
||||
int sversion; |
||||
|
||||
/*
|
||||
* Private data pointer for use by a validator module. This can be used to |
||||
* store state for the module that will be passed to each of its |
||||
* callbacks. |
||||
*/ |
||||
void *private_data; |
||||
} ValidatorModuleState; |
||||
|
||||
typedef struct ValidatorModuleResult |
||||
{ |
||||
/*
|
||||
* Should be set to true if the token carries sufficient permissions for |
||||
* the bearer to connect. |
||||
*/ |
||||
bool authorized; |
||||
|
||||
/*
|
||||
* If the token authenticates the user, this should be set to a palloc'd |
||||
* string containing the SYSTEM_USER to use for HBA mapping. Consider |
||||
* setting this even if result->authorized is false so that DBAs may use |
||||
* the logs to match end users to token failures. |
||||
* |
||||
* This is required if the module is not configured for ident mapping |
||||
* delegation. See the validator module documentation for details. |
||||
*/ |
||||
char *authn_id; |
||||
} ValidatorModuleResult; |
||||
|
||||
/*
|
||||
* Validator module callbacks |
||||
* |
||||
* These callback functions should be defined by validator modules and returned |
||||
* via _PG_oauth_validator_module_init(). ValidatorValidateCB is the only |
||||
* required callback. For more information about the purpose of each callback, |
||||
* refer to the OAuth validator modules documentation. |
||||
*/ |
||||
typedef void (*ValidatorStartupCB) (ValidatorModuleState *state); |
||||
typedef void (*ValidatorShutdownCB) (ValidatorModuleState *state); |
||||
typedef bool (*ValidatorValidateCB) (const ValidatorModuleState *state, |
||||
const char *token, const char *role, |
||||
ValidatorModuleResult *result); |
||||
|
||||
/*
|
||||
* Identifies the compiled ABI version of the validator module. Since the server |
||||
* already enforces the PG_MODULE_MAGIC number for modules across major |
||||
* versions, this is reserved for emergency use within a stable release line. |
||||
* May it never need to change. |
||||
*/ |
||||
#define PG_OAUTH_VALIDATOR_MAGIC 0x20250220 |
||||
|
||||
typedef struct OAuthValidatorCallbacks |
||||
{ |
||||
uint32 magic; /* must be set to PG_OAUTH_VALIDATOR_MAGIC */ |
||||
|
||||
ValidatorStartupCB startup_cb; |
||||
ValidatorShutdownCB shutdown_cb; |
||||
ValidatorValidateCB validate_cb; |
||||
} OAuthValidatorCallbacks; |
||||
|
||||
/*
|
||||
* Type of the shared library symbol _PG_oauth_validator_module_init which is |
||||
* required for all validator modules. This function will be invoked during |
||||
* module loading. |
||||
*/ |
||||
typedef const OAuthValidatorCallbacks *(*OAuthValidatorModuleInit) (void); |
||||
extern PGDLLEXPORT const OAuthValidatorCallbacks *_PG_oauth_validator_module_init(void); |
||||
|
||||
/* Implementation */ |
||||
extern const pg_be_sasl_mech pg_be_oauth_mech; |
||||
|
||||
/*
|
||||
* Ensure a validator named in the HBA is permitted by the configuration. |
||||
*/ |
||||
extern bool check_oauth_validator(HbaLine *hba, int elevel, char **err_msg); |
||||
|
||||
#endif /* PG_OAUTH_H */ |
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,46 @@ |
||||
/*-------------------------------------------------------------------------
|
||||
* |
||||
* fe-auth-oauth.h |
||||
* |
||||
* Definitions for OAuth authentication implementations |
||||
* |
||||
* Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group |
||||
* Portions Copyright (c) 1994, Regents of the University of California |
||||
* |
||||
* src/interfaces/libpq/fe-auth-oauth.h |
||||
* |
||||
*------------------------------------------------------------------------- |
||||
*/ |
||||
|
||||
#ifndef FE_AUTH_OAUTH_H |
||||
#define FE_AUTH_OAUTH_H |
||||
|
||||
#include "libpq-fe.h" |
||||
#include "libpq-int.h" |
||||
|
||||
|
||||
enum fe_oauth_step |
||||
{ |
||||
FE_OAUTH_INIT, |
||||
FE_OAUTH_BEARER_SENT, |
||||
FE_OAUTH_REQUESTING_TOKEN, |
||||
FE_OAUTH_SERVER_ERROR, |
||||
}; |
||||
|
||||
typedef struct |
||||
{ |
||||
enum fe_oauth_step step; |
||||
|
||||
PGconn *conn; |
||||
void *async_ctx; |
||||
} fe_oauth_state; |
||||
|
||||
extern PostgresPollingStatusType pg_fe_run_oauth_flow(PGconn *conn); |
||||
extern void pg_fe_cleanup_oauth_flow(PGconn *conn); |
||||
extern void pqClearOAuthToken(PGconn *conn); |
||||
extern bool oauth_unsafe_debugging_enabled(void); |
||||
|
||||
/* Mechanisms in fe-auth-oauth.c */ |
||||
extern const pg_fe_sasl_mech pg_oauth_mech; |
||||
|
||||
#endif /* FE_AUTH_OAUTH_H */ |
@ -0,0 +1,4 @@ |
||||
# Generated subdirectories |
||||
/log/ |
||||
/results/ |
||||
/tmp_check/ |
@ -0,0 +1,40 @@ |
||||
#-------------------------------------------------------------------------
|
||||
#
|
||||
# Makefile for src/test/modules/oauth_validator
|
||||
#
|
||||
# Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group
|
||||
# Portions Copyright (c) 1994, Regents of the University of California
|
||||
#
|
||||
# src/test/modules/oauth_validator/Makefile
|
||||
#
|
||||
#-------------------------------------------------------------------------
|
||||
|
||||
MODULES = validator fail_validator magic_validator
|
||||
PGFILEDESC = "validator - test OAuth validator module"
|
||||
|
||||
PROGRAM = oauth_hook_client
|
||||
PGAPPICON = win32
|
||||
OBJS = $(WIN32RES) oauth_hook_client.o
|
||||
|
||||
PG_CPPFLAGS = -I$(libpq_srcdir)
|
||||
PG_LIBS_INTERNAL += $(libpq_pgport)
|
||||
|
||||
NO_INSTALLCHECK = 1
|
||||
|
||||
TAP_TESTS = 1
|
||||
|
||||
ifdef USE_PGXS |
||||
PG_CONFIG = pg_config
|
||||
PGXS := $(shell $(PG_CONFIG) --pgxs)
|
||||
include $(PGXS) |
||||
else |
||||
subdir = src/test/modules/oauth_validator
|
||||
top_builddir = ../../../..
|
||||
include $(top_builddir)/src/Makefile.global |
||||
include $(top_srcdir)/contrib/contrib-global.mk |
||||
|
||||
export PYTHON |
||||
export with_libcurl |
||||
export with_python |
||||
|
||||
endif |
@ -0,0 +1,13 @@ |
||||
Test programs and libraries for OAuth |
||||
------------------------------------- |
||||
|
||||
This folder contains tests for the client- and server-side OAuth |
||||
implementations. Most tests are run end-to-end to test both simultaneously. The |
||||
tests in t/001_server use a mock OAuth authorization server, implemented jointly |
||||
by t/OAuth/Server.pm and t/oauth_server.py, to run the libpq Device |
||||
Authorization flow. The tests in t/002_client exercise custom OAuth flows and |
||||
don't need an authorization server. |
||||
|
||||
Tests in this folder require 'oauth' to be present in PG_TEST_EXTRA, since |
||||
HTTPS servers listening on localhost with TCP/IP sockets will be started. A |
||||
Python installation is required to run the mock authorization server. |
@ -0,0 +1,47 @@ |
||||
/*-------------------------------------------------------------------------
|
||||
* |
||||
* fail_validator.c |
||||
* Test module for serverside OAuth token validation callbacks, which is |
||||
* guaranteed to always fail in the validation callback |
||||
* |
||||
* Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group |
||||
* Portions Copyright (c) 1994, Regents of the University of California |
||||
* |
||||
* src/test/modules/oauth_validator/fail_validator.c |
||||
* |
||||
*------------------------------------------------------------------------- |
||||
*/ |
||||
|
||||
#include "postgres.h" |
||||
|
||||
#include "fmgr.h" |
||||
#include "libpq/oauth.h" |
||||
|
||||
PG_MODULE_MAGIC; |
||||
|
||||
static bool fail_token(const ValidatorModuleState *state, |
||||
const char *token, |
||||
const char *role, |
||||
ValidatorModuleResult *result); |
||||
|
||||
/* Callback implementations (we only need the main one) */ |
||||
static const OAuthValidatorCallbacks validator_callbacks = { |
||||
PG_OAUTH_VALIDATOR_MAGIC, |
||||
|
||||
.validate_cb = fail_token, |
||||
}; |
||||
|
||||
const OAuthValidatorCallbacks * |
||||
_PG_oauth_validator_module_init(void) |
||||
{ |
||||
return &validator_callbacks; |
||||
} |
||||
|
||||
static bool |
||||
fail_token(const ValidatorModuleState *state, |
||||
const char *token, const char *role, |
||||
ValidatorModuleResult *res) |
||||
{ |
||||
elog(FATAL, "fail_validator: sentinel error"); |
||||
pg_unreachable(); |
||||
} |
@ -0,0 +1,48 @@ |
||||
/*-------------------------------------------------------------------------
|
||||
* |
||||
* magic_validator.c |
||||
* Test module for serverside OAuth token validation callbacks, which |
||||
* should fail due to using the wrong PG_OAUTH_VALIDATOR_MAGIC marker |
||||
* and thus the wrong ABI version |
||||
* |
||||
* Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group |
||||
* Portions Copyright (c) 1994, Regents of the University of California |
||||
* |
||||
* src/test/modules/oauth_validator/magic_validator.c |
||||
* |
||||
*------------------------------------------------------------------------- |
||||
*/ |
||||
|
||||
#include "postgres.h" |
||||
|
||||
#include "fmgr.h" |
||||
#include "libpq/oauth.h" |
||||
|
||||
PG_MODULE_MAGIC; |
||||
|
||||
static bool validate_token(const ValidatorModuleState *state, |
||||
const char *token, |
||||
const char *role, |
||||
ValidatorModuleResult *result); |
||||
|
||||
/* Callback implementations (we only need the main one) */ |
||||
static const OAuthValidatorCallbacks validator_callbacks = { |
||||
0xdeadbeef, |
||||
|
||||
.validate_cb = validate_token, |
||||
}; |
||||
|
||||
const OAuthValidatorCallbacks * |
||||
_PG_oauth_validator_module_init(void) |
||||
{ |
||||
return &validator_callbacks; |
||||
} |
||||
|
||||
static bool |
||||
validate_token(const ValidatorModuleState *state, |
||||
const char *token, const char *role, |
||||
ValidatorModuleResult *res) |
||||
{ |
||||
elog(FATAL, "magic_validator: this should be unreachable"); |
||||
pg_unreachable(); |
||||
} |
@ -0,0 +1,85 @@ |
||||
# Copyright (c) 2025, PostgreSQL Global Development Group |
||||
|
||||
validator_sources = files( |
||||
'validator.c', |
||||
) |
||||
|
||||
if host_system == 'windows' |
||||
validator_sources += rc_lib_gen.process(win32ver_rc, extra_args: [ |
||||
'--NAME', 'validator', |
||||
'--FILEDESC', 'validator - test OAuth validator module',]) |
||||
endif |
||||
|
||||
validator = shared_module('validator', |
||||
validator_sources, |
||||
kwargs: pg_test_mod_args, |
||||
) |
||||
test_install_libs += validator |
||||
|
||||
fail_validator_sources = files( |
||||
'fail_validator.c', |
||||
) |
||||
|
||||
if host_system == 'windows' |
||||
fail_validator_sources += rc_lib_gen.process(win32ver_rc, extra_args: [ |
||||
'--NAME', 'fail_validator', |
||||
'--FILEDESC', 'fail_validator - failing OAuth validator module',]) |
||||
endif |
||||
|
||||
fail_validator = shared_module('fail_validator', |
||||
fail_validator_sources, |
||||
kwargs: pg_test_mod_args, |
||||
) |
||||
test_install_libs += fail_validator |
||||
|
||||
magic_validator_sources = files( |
||||
'magic_validator.c', |
||||
) |
||||
|
||||
if host_system == 'windows' |
||||
magic_validator_sources += rc_lib_gen.process(win32ver_rc, extra_args: [ |
||||
'--NAME', 'magic_validator', |
||||
'--FILEDESC', 'magic_validator - ABI incompatible OAuth validator module',]) |
||||
endif |
||||
|
||||
magic_validator = shared_module('magic_validator', |
||||
magic_validator_sources, |
||||
kwargs: pg_test_mod_args, |
||||
) |
||||
test_install_libs += magic_validator |
||||
|
||||
oauth_hook_client_sources = files( |
||||
'oauth_hook_client.c', |
||||
) |
||||
|
||||
if host_system == 'windows' |
||||
oauth_hook_client_sources += rc_bin_gen.process(win32ver_rc, extra_args: [ |
||||
'--NAME', 'oauth_hook_client', |
||||
'--FILEDESC', 'oauth_hook_client - test program for libpq OAuth hooks',]) |
||||
endif |
||||
|
||||
oauth_hook_client = executable('oauth_hook_client', |
||||
oauth_hook_client_sources, |
||||
dependencies: [frontend_code, libpq], |
||||
kwargs: default_bin_args + { |
||||
'install': false, |
||||
}, |
||||
) |
||||
testprep_targets += oauth_hook_client |
||||
|
||||
tests += { |
||||
'name': 'oauth_validator', |
||||
'sd': meson.current_source_dir(), |
||||
'bd': meson.current_build_dir(), |
||||
'tap': { |
||||
'tests': [ |
||||
't/001_server.pl', |
||||
't/002_client.pl', |
||||
], |
||||
'env': { |
||||
'PYTHON': python.path(), |
||||
'with_libcurl': libcurl.found() ? 'yes' : 'no', |
||||
'with_python': 'yes', |
||||
}, |
||||
}, |
||||
} |
@ -0,0 +1,293 @@ |
||||
/*-------------------------------------------------------------------------
|
||||
* |
||||
* oauth_hook_client.c |
||||
* Test driver for t/002_client.pl, which verifies OAuth hook |
||||
* functionality in libpq. |
||||
* |
||||
* Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group |
||||
* Portions Copyright (c) 1994, Regents of the University of California |
||||
* |
||||
* |
||||
* IDENTIFICATION |
||||
* src/test/modules/oauth_validator/oauth_hook_client.c |
||||
* |
||||
*------------------------------------------------------------------------- |
||||
*/ |
||||
|
||||
#include "postgres_fe.h" |
||||
|
||||
#include <sys/socket.h> |
||||
|
||||
#include "getopt_long.h" |
||||
#include "libpq-fe.h" |
||||
|
||||
static int handle_auth_data(PGauthData type, PGconn *conn, void *data); |
||||
static PostgresPollingStatusType async_cb(PGconn *conn, |
||||
PGoauthBearerRequest *req, |
||||
pgsocket *altsock); |
||||
static PostgresPollingStatusType misbehave_cb(PGconn *conn, |
||||
PGoauthBearerRequest *req, |
||||
pgsocket *altsock); |
||||
|
||||
static void |
||||
usage(char *argv[]) |
||||
{ |
||||
printf("usage: %s [flags] CONNINFO\n\n", argv[0]); |
||||
|
||||
printf("recognized flags:\n"); |
||||
printf(" -h, --help show this message\n"); |
||||
printf(" --expected-scope SCOPE fail if received scopes do not match SCOPE\n"); |
||||
printf(" --expected-uri URI fail if received configuration link does not match URI\n"); |
||||
printf(" --misbehave=MODE have the hook fail required postconditions\n" |
||||
" (MODEs: no-hook, fail-async, no-token, no-socket)\n"); |
||||
printf(" --no-hook don't install OAuth hooks\n"); |
||||
printf(" --hang-forever don't ever return a token (combine with connect_timeout)\n"); |
||||
printf(" --token TOKEN use the provided TOKEN value\n"); |
||||
printf(" --stress-async busy-loop on PQconnectPoll rather than polling\n"); |
||||
} |
||||
|
||||
/* --options */ |
||||
static bool no_hook = false; |
||||
static bool hang_forever = false; |
||||
static bool stress_async = false; |
||||
static const char *expected_uri = NULL; |
||||
static const char *expected_scope = NULL; |
||||
static const char *misbehave_mode = NULL; |
||||
static char *token = NULL; |
||||
|
||||
int |
||||
main(int argc, char *argv[]) |
||||
{ |
||||
static const struct option long_options[] = { |
||||
{"help", no_argument, NULL, 'h'}, |
||||
|
||||
{"expected-scope", required_argument, NULL, 1000}, |
||||
{"expected-uri", required_argument, NULL, 1001}, |
||||
{"no-hook", no_argument, NULL, 1002}, |
||||
{"token", required_argument, NULL, 1003}, |
||||
{"hang-forever", no_argument, NULL, 1004}, |
||||
{"misbehave", required_argument, NULL, 1005}, |
||||
{"stress-async", no_argument, NULL, 1006}, |
||||
{0} |
||||
}; |
||||
|
||||
const char *conninfo; |
||||
PGconn *conn; |
||||
int c; |
||||
|
||||
while ((c = getopt_long(argc, argv, "h", long_options, NULL)) != -1) |
||||
{ |
||||
switch (c) |
||||
{ |
||||
case 'h': |
||||
usage(argv); |
||||
return 0; |
||||
|
||||
case 1000: /* --expected-scope */ |
||||
expected_scope = optarg; |
||||
break; |
||||
|
||||
case 1001: /* --expected-uri */ |
||||
expected_uri = optarg; |
||||
break; |
||||
|
||||
case 1002: /* --no-hook */ |
||||
no_hook = true; |
||||
break; |
||||
|
||||
case 1003: /* --token */ |
||||
token = optarg; |
||||
break; |
||||
|
||||
case 1004: /* --hang-forever */ |
||||
hang_forever = true; |
||||
break; |
||||
|
||||
case 1005: /* --misbehave */ |
||||
misbehave_mode = optarg; |
||||
break; |
||||
|
||||
case 1006: /* --stress-async */ |
||||
stress_async = true; |
||||
break; |
||||
|
||||
default: |
||||
usage(argv); |
||||
return 1; |
||||
} |
||||
} |
||||
|
||||
if (argc != optind + 1) |
||||
{ |
||||
usage(argv); |
||||
return 1; |
||||
} |
||||
|
||||
conninfo = argv[optind]; |
||||
|
||||
/* Set up our OAuth hooks. */ |
||||
PQsetAuthDataHook(handle_auth_data); |
||||
|
||||
/* Connect. (All the actual work is in the hook.) */ |
||||
if (stress_async) |
||||
{ |
||||
/*
|
||||
* Perform an asynchronous connection, busy-looping on PQconnectPoll() |
||||
* without actually waiting on socket events. This stresses code paths |
||||
* that rely on asynchronous work to be done before continuing with |
||||
* the next step in the flow. |
||||
*/ |
||||
PostgresPollingStatusType res; |
||||
|
||||
conn = PQconnectStart(conninfo); |
||||
|
||||
do |
||||
{ |
||||
res = PQconnectPoll(conn); |
||||
} while (res != PGRES_POLLING_FAILED && res != PGRES_POLLING_OK); |
||||
} |
||||
else |
||||
{ |
||||
/* Perform a standard synchronous connection. */ |
||||
conn = PQconnectdb(conninfo); |
||||
} |
||||
|
||||
if (PQstatus(conn) != CONNECTION_OK) |
||||
{ |
||||
fprintf(stderr, "connection to database failed: %s\n", |
||||
PQerrorMessage(conn)); |
||||
PQfinish(conn); |
||||
return 1; |
||||
} |
||||
|
||||
printf("connection succeeded\n"); |
||||
PQfinish(conn); |
||||
return 0; |
||||
} |
||||
|
||||
/*
|
||||
* PQauthDataHook implementation. Replaces the default client flow by handling |
||||
* PQAUTHDATA_OAUTH_BEARER_TOKEN. |
||||
*/ |
||||
static int |
||||
handle_auth_data(PGauthData type, PGconn *conn, void *data) |
||||
{ |
||||
PGoauthBearerRequest *req = data; |
||||
|
||||
if (no_hook || (type != PQAUTHDATA_OAUTH_BEARER_TOKEN)) |
||||
return 0; |
||||
|
||||
if (hang_forever) |
||||
{ |
||||
/* Start asynchronous processing. */ |
||||
req->async = async_cb; |
||||
return 1; |
||||
} |
||||
|
||||
if (misbehave_mode) |
||||
{ |
||||
if (strcmp(misbehave_mode, "no-hook") != 0) |
||||
req->async = misbehave_cb; |
||||
return 1; |
||||
} |
||||
|
||||
if (expected_uri) |
||||
{ |
||||
if (!req->openid_configuration) |
||||
{ |
||||
fprintf(stderr, "expected URI \"%s\", got NULL\n", expected_uri); |
||||
return -1; |
||||
} |
||||
|
||||
if (strcmp(expected_uri, req->openid_configuration) != 0) |
||||
{ |
||||
fprintf(stderr, "expected URI \"%s\", got \"%s\"\n", expected_uri, req->openid_configuration); |
||||
return -1; |
||||
} |
||||
} |
||||
|
||||
if (expected_scope) |
||||
{ |
||||
if (!req->scope) |
||||
{ |
||||
fprintf(stderr, "expected scope \"%s\", got NULL\n", expected_scope); |
||||
return -1; |
||||
} |
||||
|
||||
if (strcmp(expected_scope, req->scope) != 0) |
||||
{ |
||||
fprintf(stderr, "expected scope \"%s\", got \"%s\"\n", expected_scope, req->scope); |
||||
return -1; |
||||
} |
||||
} |
||||
|
||||
req->token = token; |
||||
return 1; |
||||
} |
||||
|
||||
static PostgresPollingStatusType |
||||
async_cb(PGconn *conn, PGoauthBearerRequest *req, pgsocket *altsock) |
||||
{ |
||||
if (hang_forever) |
||||
{ |
||||
/*
|
||||
* This code tests that nothing is interfering with libpq's handling |
||||
* of connect_timeout. |
||||
*/ |
||||
static pgsocket sock = PGINVALID_SOCKET; |
||||
|
||||
if (sock == PGINVALID_SOCKET) |
||||
{ |
||||
/* First call. Create an unbound socket to wait on. */ |
||||
#ifdef WIN32 |
||||
WSADATA wsaData; |
||||
int err; |
||||
|
||||
err = WSAStartup(MAKEWORD(2, 2), &wsaData); |
||||
if (err) |
||||
{ |
||||
perror("WSAStartup failed"); |
||||
return PGRES_POLLING_FAILED; |
||||
} |
||||
#endif |
||||
sock = socket(AF_INET, SOCK_DGRAM, 0); |
||||
if (sock == PGINVALID_SOCKET) |
||||
{ |
||||
perror("failed to create datagram socket"); |
||||
return PGRES_POLLING_FAILED; |
||||
} |
||||
} |
||||
|
||||
/* Make libpq wait on the (unreadable) socket. */ |
||||
*altsock = sock; |
||||
return PGRES_POLLING_READING; |
||||
} |
||||
|
||||
req->token = token; |
||||
return PGRES_POLLING_OK; |
||||
} |
||||
|
||||
static PostgresPollingStatusType |
||||
misbehave_cb(PGconn *conn, PGoauthBearerRequest *req, pgsocket *altsock) |
||||
{ |
||||
if (strcmp(misbehave_mode, "fail-async") == 0) |
||||
{ |
||||
/* Just fail "normally". */ |
||||
return PGRES_POLLING_FAILED; |
||||
} |
||||
else if (strcmp(misbehave_mode, "no-token") == 0) |
||||
{ |
||||
/* Callbacks must assign req->token before returning OK. */ |
||||
return PGRES_POLLING_OK; |
||||
} |
||||
else if (strcmp(misbehave_mode, "no-socket") == 0) |
||||
{ |
||||
/* Callbacks must assign *altsock before asking for polling. */ |
||||
return PGRES_POLLING_READING; |
||||
} |
||||
else |
||||
{ |
||||
fprintf(stderr, "unrecognized --misbehave mode: %s\n", misbehave_mode); |
||||
exit(1); |
||||
} |
||||
} |
@ -0,0 +1,594 @@ |
||||
|
||||
# |
||||
# Tests the libpq builtin OAuth flow, as well as server-side HBA and validator |
||||
# setup. |
||||
# |
||||
# Copyright (c) 2021-2025, PostgreSQL Global Development Group |
||||
# |
||||
|
||||
use strict; |
||||
use warnings FATAL => 'all'; |
||||
|
||||
use JSON::PP qw(encode_json); |
||||
use MIME::Base64 qw(encode_base64); |
||||
use PostgreSQL::Test::Cluster; |
||||
use PostgreSQL::Test::Utils; |
||||
use Test::More; |
||||
|
||||
use FindBin; |
||||
use lib $FindBin::RealBin; |
||||
|
||||
use OAuth::Server; |
||||
|
||||
if (!$ENV{PG_TEST_EXTRA} || $ENV{PG_TEST_EXTRA} !~ /\boauth\b/) |
||||
{ |
||||
plan skip_all => |
||||
'Potentially unsafe test oauth not enabled in PG_TEST_EXTRA'; |
||||
} |
||||
|
||||
if ($windows_os) |
||||
{ |
||||
plan skip_all => 'OAuth server-side tests are not supported on Windows'; |
||||
} |
||||
|
||||
if ($ENV{with_libcurl} ne 'yes') |
||||
{ |
||||
plan skip_all => 'client-side OAuth not supported by this build'; |
||||
} |
||||
|
||||
if ($ENV{with_python} ne 'yes') |
||||
{ |
||||
plan skip_all => 'OAuth tests require --with-python to run'; |
||||
} |
||||
|
||||
my $node = PostgreSQL::Test::Cluster->new('primary'); |
||||
$node->init; |
||||
$node->append_conf('postgresql.conf', "log_connections = on\n"); |
||||
$node->append_conf('postgresql.conf', |
||||
"oauth_validator_libraries = 'validator'\n"); |
||||
$node->start; |
||||
|
||||
$node->safe_psql('postgres', 'CREATE USER test;'); |
||||
$node->safe_psql('postgres', 'CREATE USER testalt;'); |
||||
$node->safe_psql('postgres', 'CREATE USER testparam;'); |
||||
|
||||
# Save a background connection for later configuration changes. |
||||
my $bgconn = $node->background_psql('postgres'); |
||||
|
||||
my $webserver = OAuth::Server->new(); |
||||
$webserver->run(); |
||||
|
||||
END |
||||
{ |
||||
my $exit_code = $?; |
||||
|
||||
$webserver->stop() if defined $webserver; # might have been SKIP'd |
||||
|
||||
$? = $exit_code; |
||||
} |
||||
|
||||
my $port = $webserver->port(); |
||||
my $issuer = "http://localhost:$port"; |
||||
|
||||
unlink($node->data_dir . '/pg_hba.conf'); |
||||
$node->append_conf( |
||||
'pg_hba.conf', qq{ |
||||
local all test oauth issuer="$issuer" scope="openid postgres" |
||||
local all testalt oauth issuer="$issuer/.well-known/oauth-authorization-server/alternate" scope="openid postgres alt" |
||||
local all testparam oauth issuer="$issuer/param" scope="openid postgres" |
||||
}); |
||||
$node->reload; |
||||
|
||||
my $log_start = $node->wait_for_log(qr/reloading configuration files/); |
||||
|
||||
# Check pg_hba_file_rules() support. |
||||
my $contents = $bgconn->query_safe( |
||||
qq(SELECT rule_number, auth_method, options |
||||
FROM pg_hba_file_rules |
||||
ORDER BY rule_number;)); |
||||
is( $contents, |
||||
qq{1|oauth|\{issuer=$issuer,"scope=openid postgres",validator=validator\} |
||||
2|oauth|\{issuer=$issuer/.well-known/oauth-authorization-server/alternate,"scope=openid postgres alt",validator=validator\} |
||||
3|oauth|\{issuer=$issuer/param,"scope=openid postgres",validator=validator\}}, |
||||
"pg_hba_file_rules recreates OAuth HBA settings"); |
||||
|
||||
# To test against HTTP rather than HTTPS, we need to enable PGOAUTHDEBUG. But |
||||
# first, check to make sure the client refuses such connections by default. |
||||
$node->connect_fails( |
||||
"user=test dbname=postgres oauth_issuer=$issuer oauth_client_id=f02c6361-0635", |
||||
"HTTPS is required without debug mode", |
||||
expected_stderr => |
||||
qr@OAuth discovery URI "\Q$issuer\E/.well-known/openid-configuration" must use HTTPS@ |
||||
); |
||||
|
||||
$ENV{PGOAUTHDEBUG} = "UNSAFE"; |
||||
|
||||
my $user = "test"; |
||||
$node->connect_ok( |
||||
"user=$user dbname=postgres oauth_issuer=$issuer oauth_client_id=f02c6361-0635", |
||||
"connect as test", |
||||
expected_stderr => |
||||
qr@Visit https://example\.com/ and enter the code: postgresuser@, |
||||
log_like => [ |
||||
qr/oauth_validator: token="9243959234", role="$user"/, |
||||
qr/oauth_validator: issuer="\Q$issuer\E", scope="openid postgres"/, |
||||
qr/connection authenticated: identity="test" method=oauth/, |
||||
qr/connection authorized/, |
||||
]); |
||||
|
||||
# The /alternate issuer uses slightly different parameters, along with an |
||||
# OAuth-style discovery document. |
||||
$user = "testalt"; |
||||
$node->connect_ok( |
||||
"user=$user dbname=postgres oauth_issuer=$issuer/alternate oauth_client_id=f02c6361-0636", |
||||
"connect as testalt", |
||||
expected_stderr => |
||||
qr@Visit https://example\.org/ and enter the code: postgresuser@, |
||||
log_like => [ |
||||
qr/oauth_validator: token="9243959234-alt", role="$user"/, |
||||
qr|oauth_validator: issuer="\Q$issuer/.well-known/oauth-authorization-server/alternate\E", scope="openid postgres alt"|, |
||||
qr/connection authenticated: identity="testalt" method=oauth/, |
||||
qr/connection authorized/, |
||||
]); |
||||
|
||||
# The issuer linked by the server must match the client's oauth_issuer setting. |
||||
$node->connect_fails( |
||||
"user=$user dbname=postgres oauth_issuer=$issuer oauth_client_id=f02c6361-0636", |
||||
"oauth_issuer must match discovery", |
||||
expected_stderr => |
||||
qr@server's discovery document at \Q$issuer/.well-known/oauth-authorization-server/alternate\E \(issuer "\Q$issuer/alternate\E"\) is incompatible with oauth_issuer \(\Q$issuer\E\)@ |
||||
); |
||||
|
||||
# Test require_auth settings against OAUTHBEARER. |
||||
my @cases = ( |
||||
{ require_auth => "oauth" }, |
||||
{ require_auth => "oauth,scram-sha-256" }, |
||||
{ require_auth => "password,oauth" }, |
||||
{ require_auth => "none,oauth" }, |
||||
{ require_auth => "!scram-sha-256" }, |
||||
{ require_auth => "!none" }, |
||||
|
||||
{ |
||||
require_auth => "!oauth", |
||||
failure => qr/server requested OAUTHBEARER authentication/ |
||||
}, |
||||
{ |
||||
require_auth => "scram-sha-256", |
||||
failure => qr/server requested OAUTHBEARER authentication/ |
||||
}, |
||||
{ |
||||
require_auth => "!password,!oauth", |
||||
failure => qr/server requested OAUTHBEARER authentication/ |
||||
}, |
||||
{ |
||||
require_auth => "none", |
||||
failure => qr/server requested SASL authentication/ |
||||
}, |
||||
{ |
||||
require_auth => "!oauth,!scram-sha-256", |
||||
failure => qr/server requested SASL authentication/ |
||||
}); |
||||
|
||||
$user = "test"; |
||||
foreach my $c (@cases) |
||||
{ |
||||
my $connstr = |
||||
"user=$user dbname=postgres oauth_issuer=$issuer oauth_client_id=f02c6361-0635 require_auth=$c->{'require_auth'}"; |
||||
|
||||
if (defined $c->{'failure'}) |
||||
{ |
||||
$node->connect_fails( |
||||
$connstr, |
||||
"require_auth=$c->{'require_auth'} fails", |
||||
expected_stderr => $c->{'failure'}); |
||||
} |
||||
else |
||||
{ |
||||
$node->connect_ok( |
||||
$connstr, |
||||
"require_auth=$c->{'require_auth'} succeeds", |
||||
expected_stderr => |
||||
qr@Visit https://example\.com/ and enter the code: postgresuser@ |
||||
); |
||||
} |
||||
} |
||||
|
||||
# Make sure the client_id and secret are correctly encoded. $vschars contains |
||||
# every allowed character for a client_id/_secret (the "VSCHAR" class). |
||||
# $vschars_esc is additionally backslash-escaped for inclusion in a |
||||
# single-quoted connection string. |
||||
my $vschars = |
||||
" !\"#\$%&'()*+,-./0123456789:;<=>?\@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~"; |
||||
my $vschars_esc = |
||||
" !\"#\$%&\\'()*+,-./0123456789:;<=>?\@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\\\]^_`abcdefghijklmnopqrstuvwxyz{|}~"; |
||||
|
||||
$node->connect_ok( |
||||
"user=$user dbname=postgres oauth_issuer=$issuer oauth_client_id='$vschars_esc'", |
||||
"escapable characters: client_id", |
||||
expected_stderr => |
||||
qr@Visit https://example\.com/ and enter the code: postgresuser@); |
||||
$node->connect_ok( |
||||
"user=$user dbname=postgres oauth_issuer=$issuer oauth_client_id='$vschars_esc' oauth_client_secret='$vschars_esc'", |
||||
"escapable characters: client_id and secret", |
||||
expected_stderr => |
||||
qr@Visit https://example\.com/ and enter the code: postgresuser@); |
||||
|
||||
# |
||||
# Further tests rely on support for specific behaviors in oauth_server.py. To |
||||
# trigger these behaviors, we ask for the special issuer .../param (which is set |
||||
# up in HBA for the testparam user) and encode magic instructions into the |
||||
# oauth_client_id. |
||||
# |
||||
|
||||
my $common_connstr = |
||||
"user=testparam dbname=postgres oauth_issuer=$issuer/param "; |
||||
my $base_connstr = $common_connstr; |
||||
|
||||
sub connstr |
||||
{ |
||||
my (%params) = @_; |
||||
|
||||
my $json = encode_json(\%params); |
||||
my $encoded = encode_base64($json, ""); |
||||
|
||||
return "$base_connstr oauth_client_id=$encoded"; |
||||
} |
||||
|
||||
# Make sure the param system works end-to-end first. |
||||
$node->connect_ok( |
||||
connstr(), |
||||
"connect to /param", |
||||
expected_stderr => |
||||
qr@Visit https://example\.com/ and enter the code: postgresuser@); |
||||
|
||||
$node->connect_ok( |
||||
connstr(stage => 'token', retries => 1), |
||||
"token retry", |
||||
expected_stderr => |
||||
qr@Visit https://example\.com/ and enter the code: postgresuser@); |
||||
$node->connect_ok( |
||||
connstr(stage => 'token', retries => 2), |
||||
"token retry (twice)", |
||||
expected_stderr => |
||||
qr@Visit https://example\.com/ and enter the code: postgresuser@); |
||||
$node->connect_ok( |
||||
connstr(stage => 'all', retries => 1, interval => 2), |
||||
"token retry (two second interval)", |
||||
expected_stderr => |
||||
qr@Visit https://example\.com/ and enter the code: postgresuser@); |
||||
$node->connect_ok( |
||||
connstr(stage => 'all', retries => 1, interval => JSON::PP::null), |
||||
"token retry (default interval)", |
||||
expected_stderr => |
||||
qr@Visit https://example\.com/ and enter the code: postgresuser@); |
||||
|
||||
$node->connect_ok( |
||||
connstr(stage => 'all', content_type => 'application/json;charset=utf-8'), |
||||
"content type with charset", |
||||
expected_stderr => |
||||
qr@Visit https://example\.com/ and enter the code: postgresuser@); |
||||
$node->connect_ok( |
||||
connstr( |
||||
stage => 'all', |
||||
content_type => "application/json \t;\t charset=utf-8"), |
||||
"content type with charset (whitespace)", |
||||
expected_stderr => |
||||
qr@Visit https://example\.com/ and enter the code: postgresuser@); |
||||
$node->connect_ok( |
||||
connstr(stage => 'device', uri_spelling => "verification_url"), |
||||
"alternative spelling of verification_uri", |
||||
expected_stderr => |
||||
qr@Visit https://example\.com/ and enter the code: postgresuser@); |
||||
|
||||
$node->connect_fails( |
||||
connstr(stage => 'device', huge_response => JSON::PP::true), |
||||
"bad device authz response: overlarge JSON", |
||||
expected_stderr => |
||||
qr/failed to obtain device authorization: response is too large/); |
||||
$node->connect_fails( |
||||
connstr(stage => 'token', huge_response => JSON::PP::true), |
||||
"bad token response: overlarge JSON", |
||||
expected_stderr => |
||||
qr/failed to obtain access token: response is too large/); |
||||
|
||||
$node->connect_fails( |
||||
connstr(stage => 'device', content_type => 'text/plain'), |
||||
"bad device authz response: wrong content type", |
||||
expected_stderr => |
||||
qr/failed to parse device authorization: unexpected content type/); |
||||
$node->connect_fails( |
||||
connstr(stage => 'token', content_type => 'text/plain'), |
||||
"bad token response: wrong content type", |
||||
expected_stderr => |
||||
qr/failed to parse access token response: unexpected content type/); |
||||
$node->connect_fails( |
||||
connstr(stage => 'token', content_type => 'application/jsonx'), |
||||
"bad token response: wrong content type (correct prefix)", |
||||
expected_stderr => |
||||
qr/failed to parse access token response: unexpected content type/); |
||||
|
||||
$node->connect_fails( |
||||
connstr( |
||||
stage => 'all', |
||||
interval => ~0, |
||||
retries => 1, |
||||
retry_code => "slow_down"), |
||||
"bad token response: server overflows the device authz interval", |
||||
expected_stderr => |
||||
qr/failed to obtain access token: slow_down interval overflow/); |
||||
|
||||
$node->connect_fails( |
||||
connstr(stage => 'token', error_code => "invalid_grant"), |
||||
"bad token response: invalid_grant, no description", |
||||
expected_stderr => qr/failed to obtain access token: \(invalid_grant\)/); |
||||
$node->connect_fails( |
||||
connstr( |
||||
stage => 'token', |
||||
error_code => "invalid_grant", |
||||
error_desc => "grant expired"), |
||||
"bad token response: expired grant", |
||||
expected_stderr => |
||||
qr/failed to obtain access token: grant expired \(invalid_grant\)/); |
||||
$node->connect_fails( |
||||
connstr( |
||||
stage => 'token', |
||||
error_code => "invalid_client", |
||||
error_status => 401), |
||||
"bad token response: client authentication failure, default description", |
||||
expected_stderr => |
||||
qr/failed to obtain access token: provider requires client authentication, and no oauth_client_secret is set \(invalid_client\)/ |
||||
); |
||||
$node->connect_fails( |
||||
connstr( |
||||
stage => 'token', |
||||
error_code => "invalid_client", |
||||
error_status => 401, |
||||
error_desc => "authn failure"), |
||||
"bad token response: client authentication failure, provided description", |
||||
expected_stderr => |
||||
qr/failed to obtain access token: authn failure \(invalid_client\)/); |
||||
|
||||
$node->connect_fails( |
||||
connstr(stage => 'token', token => ""), |
||||
"server rejects access: empty token", |
||||
expected_stderr => qr/bearer authentication failed/); |
||||
$node->connect_fails( |
||||
connstr(stage => 'token', token => "****"), |
||||
"server rejects access: invalid token contents", |
||||
expected_stderr => qr/bearer authentication failed/); |
||||
|
||||
# Test behavior of the oauth_client_secret. |
||||
$base_connstr = "$common_connstr oauth_client_secret=''"; |
||||
|
||||
$node->connect_ok( |
||||
connstr(stage => 'all', expected_secret => ''), |
||||
"empty oauth_client_secret", |
||||
expected_stderr => |
||||
qr@Visit https://example\.com/ and enter the code: postgresuser@); |
||||
|
||||
$base_connstr = "$common_connstr oauth_client_secret='$vschars_esc'"; |
||||
|
||||
$node->connect_ok( |
||||
connstr(stage => 'all', expected_secret => $vschars), |
||||
"nonempty oauth_client_secret", |
||||
expected_stderr => |
||||
qr@Visit https://example\.com/ and enter the code: postgresuser@); |
||||
|
||||
$node->connect_fails( |
||||
connstr( |
||||
stage => 'token', |
||||
error_code => "invalid_client", |
||||
error_status => 401), |
||||
"bad token response: client authentication failure, default description with oauth_client_secret", |
||||
expected_stderr => |
||||
qr/failed to obtain access token: provider rejected the oauth_client_secret \(invalid_client\)/ |
||||
); |
||||
$node->connect_fails( |
||||
connstr( |
||||
stage => 'token', |
||||
error_code => "invalid_client", |
||||
error_status => 401, |
||||
error_desc => "mutual TLS required for client"), |
||||
"bad token response: client authentication failure, provided description with oauth_client_secret", |
||||
expected_stderr => |
||||
qr/failed to obtain access token: mutual TLS required for client \(invalid_client\)/ |
||||
); |
||||
|
||||
# Stress test: make sure our builtin flow operates correctly even if the client |
||||
# application isn't respecting PGRES_POLLING_READING/WRITING signals returned |
||||
# from PQconnectPoll(). |
||||
$base_connstr = |
||||
"$common_connstr port=" . $node->port . " host=" . $node->host; |
||||
my @cmd = ( |
||||
"oauth_hook_client", "--no-hook", "--stress-async", |
||||
connstr(stage => 'all', retries => 1, interval => 1)); |
||||
|
||||
note "running '" . join("' '", @cmd) . "'"; |
||||
my ($stdout, $stderr) = run_command(\@cmd); |
||||
|
||||
like($stdout, qr/connection succeeded/, "stress-async: stdout matches"); |
||||
unlike( |
||||
$stderr, |
||||
qr/connection to database failed/, |
||||
"stress-async: stderr matches"); |
||||
|
||||
# |
||||
# This section of tests reconfigures the validator module itself, rather than |
||||
# the OAuth server. |
||||
# |
||||
|
||||
# Searching the logs is easier if OAuth parameter discovery isn't cluttering |
||||
# things up; hardcode the discovery URI. (Scope is hardcoded to empty to cover |
||||
# that case as well.) |
||||
$common_connstr = |
||||
"dbname=postgres oauth_issuer=$issuer/.well-known/openid-configuration oauth_scope='' oauth_client_id=f02c6361-0635"; |
||||
|
||||
# Misbehaving validators must fail shut. |
||||
$bgconn->query_safe("ALTER SYSTEM SET oauth_validator.authn_id TO ''"); |
||||
$node->reload; |
||||
$log_start = |
||||
$node->wait_for_log(qr/reloading configuration files/, $log_start); |
||||
|
||||
$node->connect_fails( |
||||
"$common_connstr user=test", |
||||
"validator must set authn_id", |
||||
expected_stderr => qr/OAuth bearer authentication failed/, |
||||
log_like => [ |
||||
qr/connection authenticated: identity=""/, |
||||
qr/DETAIL:\s+Validator provided no identity/, |
||||
qr/FATAL:\s+OAuth bearer authentication failed/, |
||||
]); |
||||
|
||||
# Even if a validator authenticates the user, if the token isn't considered |
||||
# valid, the connection fails. |
||||
$bgconn->query_safe( |
||||
"ALTER SYSTEM SET oauth_validator.authn_id TO 'test\@example.org'"); |
||||
$bgconn->query_safe( |
||||
"ALTER SYSTEM SET oauth_validator.authorize_tokens TO false"); |
||||
$node->reload; |
||||
$log_start = |
||||
$node->wait_for_log(qr/reloading configuration files/, $log_start); |
||||
|
||||
$node->connect_fails( |
||||
"$common_connstr user=test", |
||||
"validator must authorize token explicitly", |
||||
expected_stderr => qr/OAuth bearer authentication failed/, |
||||
log_like => [ |
||||
qr/connection authenticated: identity="test\@example\.org"/, |
||||
qr/DETAIL:\s+Validator failed to authorize the provided token/, |
||||
qr/FATAL:\s+OAuth bearer authentication failed/, |
||||
]); |
||||
|
||||
# |
||||
# Test user mapping. |
||||
# |
||||
|
||||
# Allow "user@example.com" to log in under the test role. |
||||
unlink($node->data_dir . '/pg_ident.conf'); |
||||
$node->append_conf( |
||||
'pg_ident.conf', qq{ |
||||
oauthmap user\@example.com test |
||||
}); |
||||
|
||||
# test and testalt use the map; testparam uses ident delegation. |
||||
unlink($node->data_dir . '/pg_hba.conf'); |
||||
$node->append_conf( |
||||
'pg_hba.conf', qq{ |
||||
local all test oauth issuer="$issuer" scope="" map=oauthmap |
||||
local all testalt oauth issuer="$issuer" scope="" map=oauthmap |
||||
local all testparam oauth issuer="$issuer" scope="" delegate_ident_mapping=1 |
||||
}); |
||||
|
||||
# To start, have the validator use the role names as authn IDs. |
||||
$bgconn->query_safe("ALTER SYSTEM RESET oauth_validator.authn_id"); |
||||
$bgconn->query_safe("ALTER SYSTEM RESET oauth_validator.authorize_tokens"); |
||||
|
||||
$node->reload; |
||||
$log_start = |
||||
$node->wait_for_log(qr/reloading configuration files/, $log_start); |
||||
|
||||
# The test and testalt roles should no longer map correctly. |
||||
$node->connect_fails( |
||||
"$common_connstr user=test", |
||||
"mismatched username map (test)", |
||||
expected_stderr => qr/OAuth bearer authentication failed/); |
||||
$node->connect_fails( |
||||
"$common_connstr user=testalt", |
||||
"mismatched username map (testalt)", |
||||
expected_stderr => qr/OAuth bearer authentication failed/); |
||||
|
||||
# Have the validator identify the end user as user@example.com. |
||||
$bgconn->query_safe( |
||||
"ALTER SYSTEM SET oauth_validator.authn_id TO 'user\@example.com'"); |
||||
$node->reload; |
||||
$log_start = |
||||
$node->wait_for_log(qr/reloading configuration files/, $log_start); |
||||
|
||||
# Now the test role can be logged into. (testalt still can't be mapped.) |
||||
$node->connect_ok( |
||||
"$common_connstr user=test", |
||||
"matched username map (test)", |
||||
expected_stderr => |
||||
qr@Visit https://example\.com/ and enter the code: postgresuser@); |
||||
$node->connect_fails( |
||||
"$common_connstr user=testalt", |
||||
"mismatched username map (testalt)", |
||||
expected_stderr => qr/OAuth bearer authentication failed/); |
||||
|
||||
# testparam ignores the map entirely. |
||||
$node->connect_ok( |
||||
"$common_connstr user=testparam", |
||||
"delegated ident (testparam)", |
||||
expected_stderr => |
||||
qr@Visit https://example\.com/ and enter the code: postgresuser@); |
||||
|
||||
$bgconn->query_safe("ALTER SYSTEM RESET oauth_validator.authn_id"); |
||||
$node->reload; |
||||
$log_start = |
||||
$node->wait_for_log(qr/reloading configuration files/, $log_start); |
||||
|
||||
# |
||||
# Test multiple validators. |
||||
# |
||||
|
||||
$node->append_conf('postgresql.conf', |
||||
"oauth_validator_libraries = 'validator, fail_validator'\n"); |
||||
|
||||
# With multiple validators, every HBA line must explicitly declare one. |
||||
my $result = $node->restart(fail_ok => 1); |
||||
is($result, 0, |
||||
'restart fails without explicit validators in oauth HBA entries'); |
||||
|
||||
$log_start = $node->wait_for_log( |
||||
qr/authentication method "oauth" requires argument "validator" to be set/, |
||||
$log_start); |
||||
|
||||
unlink($node->data_dir . '/pg_hba.conf'); |
||||
$node->append_conf( |
||||
'pg_hba.conf', qq{ |
||||
local all test oauth validator=validator issuer="$issuer" scope="openid postgres" |
||||
local all testalt oauth validator=fail_validator issuer="$issuer/.well-known/oauth-authorization-server/alternate" scope="openid postgres alt" |
||||
}); |
||||
$node->restart; |
||||
|
||||
$log_start = $node->wait_for_log(qr/ready to accept connections/, $log_start); |
||||
|
||||
# The test user should work as before. |
||||
$user = "test"; |
||||
$node->connect_ok( |
||||
"user=$user dbname=postgres oauth_issuer=$issuer oauth_client_id=f02c6361-0635", |
||||
"validator is used for $user", |
||||
expected_stderr => |
||||
qr@Visit https://example\.com/ and enter the code: postgresuser@, |
||||
log_like => [qr/connection authorized/]); |
||||
|
||||
# testalt should be routed through the fail_validator. |
||||
$user = "testalt"; |
||||
$node->connect_fails( |
||||
"user=$user dbname=postgres oauth_issuer=$issuer/.well-known/oauth-authorization-server/alternate oauth_client_id=f02c6361-0636", |
||||
"fail_validator is used for $user", |
||||
expected_stderr => qr/FATAL:\s+fail_validator: sentinel error/); |
||||
|
||||
# |
||||
# Test ABI compatibility magic marker |
||||
# |
||||
$node->append_conf('postgresql.conf', |
||||
"oauth_validator_libraries = 'magic_validator'\n"); |
||||
unlink($node->data_dir . '/pg_hba.conf'); |
||||
$node->append_conf( |
||||
'pg_hba.conf', qq{ |
||||
local all test oauth validator=magic_validator issuer="$issuer" scope="openid postgres" |
||||
}); |
||||
$node->restart; |
||||
|
||||
$log_start = $node->wait_for_log(qr/ready to accept connections/, $log_start); |
||||
|
||||
$node->connect_fails( |
||||
"user=test dbname=postgres oauth_issuer=$issuer/.well-known/oauth-authorization-server/alternate oauth_client_id=f02c6361-0636", |
||||
"magic_validator is used for $user", |
||||
expected_stderr => |
||||
qr/FATAL:\s+OAuth validator module "magic_validator": magic number mismatch/ |
||||
); |
||||
$node->stop; |
||||
|
||||
done_testing(); |
@ -0,0 +1,154 @@ |
||||
# |
||||
# Exercises the API for custom OAuth client flows, using the oauth_hook_client |
||||
# test driver. |
||||
# |
||||
# Copyright (c) 2021-2025, PostgreSQL Global Development Group |
||||
# |
||||
|
||||
use strict; |
||||
use warnings FATAL => 'all'; |
||||
|
||||
use JSON::PP qw(encode_json); |
||||
use MIME::Base64 qw(encode_base64); |
||||
use PostgreSQL::Test::Cluster; |
||||
use PostgreSQL::Test::Utils; |
||||
use Test::More; |
||||
|
||||
if (!$ENV{PG_TEST_EXTRA} || $ENV{PG_TEST_EXTRA} !~ /\boauth\b/) |
||||
{ |
||||
plan skip_all => |
||||
'Potentially unsafe test oauth not enabled in PG_TEST_EXTRA'; |
||||
} |
||||
|
||||
# |
||||
# Cluster Setup |
||||
# |
||||
|
||||
my $node = PostgreSQL::Test::Cluster->new('primary'); |
||||
$node->init; |
||||
$node->append_conf('postgresql.conf', "log_connections = on\n"); |
||||
$node->append_conf('postgresql.conf', |
||||
"oauth_validator_libraries = 'validator'\n"); |
||||
$node->start; |
||||
|
||||
$node->safe_psql('postgres', 'CREATE USER test;'); |
||||
|
||||
# These tests don't use the builtin flow, and we don't have an authorization |
||||
# server running, so the address used here shouldn't matter. Use an invalid IP |
||||
# address, so if there's some cascade of errors that causes the client to |
||||
# attempt a connection, we'll fail noisily. |
||||
my $issuer = "https://256.256.256.256"; |
||||
my $scope = "openid postgres"; |
||||
|
||||
unlink($node->data_dir . '/pg_hba.conf'); |
||||
$node->append_conf( |
||||
'pg_hba.conf', qq{ |
||||
local all test oauth issuer="$issuer" scope="$scope" |
||||
}); |
||||
$node->reload; |
||||
|
||||
my ($log_start, $log_end); |
||||
$log_start = $node->wait_for_log(qr/reloading configuration files/); |
||||
|
||||
$ENV{PGOAUTHDEBUG} = "UNSAFE"; |
||||
|
||||
# |
||||
# Tests |
||||
# |
||||
|
||||
my $user = "test"; |
||||
my $base_connstr = $node->connstr() . " user=$user"; |
||||
my $common_connstr = |
||||
"$base_connstr oauth_issuer=$issuer oauth_client_id=myID"; |
||||
|
||||
sub test |
||||
{ |
||||
my ($test_name, %params) = @_; |
||||
|
||||
my $flags = []; |
||||
if (defined($params{flags})) |
||||
{ |
||||
$flags = $params{flags}; |
||||
} |
||||
|
||||
my @cmd = ("oauth_hook_client", @{$flags}, $common_connstr); |
||||
note "running '" . join("' '", @cmd) . "'"; |
||||
|
||||
my ($stdout, $stderr) = run_command(\@cmd); |
||||
|
||||
if (defined($params{expected_stdout})) |
||||
{ |
||||
like($stdout, $params{expected_stdout}, "$test_name: stdout matches"); |
||||
} |
||||
|
||||
if (defined($params{expected_stderr})) |
||||
{ |
||||
like($stderr, $params{expected_stderr}, "$test_name: stderr matches"); |
||||
} |
||||
else |
||||
{ |
||||
is($stderr, "", "$test_name: no stderr"); |
||||
} |
||||
} |
||||
|
||||
test( |
||||
"basic synchronous hook can provide a token", |
||||
flags => [ |
||||
"--token", "my-token", |
||||
"--expected-uri", "$issuer/.well-known/openid-configuration", |
||||
"--expected-scope", $scope, |
||||
], |
||||
expected_stdout => qr/connection succeeded/); |
||||
|
||||
$node->log_check("validator receives correct token", |
||||
$log_start, |
||||
log_like => [ qr/oauth_validator: token="my-token", role="$user"/, ]); |
||||
|
||||
if ($ENV{with_libcurl} ne 'yes') |
||||
{ |
||||
# libpq should help users out if no OAuth support is built in. |
||||
test( |
||||
"fails without custom hook installed", |
||||
flags => ["--no-hook"], |
||||
expected_stderr => |
||||
qr/no custom OAuth flows are available, and libpq was not built with libcurl support/ |
||||
); |
||||
} |
||||
|
||||
# connect_timeout should work if the flow doesn't respond. |
||||
$common_connstr = "$common_connstr connect_timeout=1"; |
||||
test( |
||||
"connect_timeout interrupts hung client flow", |
||||
flags => ["--hang-forever"], |
||||
expected_stderr => qr/failed: timeout expired/); |
||||
|
||||
# Test various misbehaviors of the client hook. |
||||
my @cases = ( |
||||
{ |
||||
flag => "--misbehave=no-hook", |
||||
expected_error => |
||||
qr/user-defined OAuth flow provided neither a token nor an async callback/, |
||||
}, |
||||
{ |
||||
flag => "--misbehave=fail-async", |
||||
expected_error => qr/user-defined OAuth flow failed/, |
||||
}, |
||||
{ |
||||
flag => "--misbehave=no-token", |
||||
expected_error => qr/user-defined OAuth flow did not provide a token/, |
||||
}, |
||||
{ |
||||
flag => "--misbehave=no-socket", |
||||
expected_error => |
||||
qr/user-defined OAuth flow did not provide a socket for polling/, |
||||
}); |
||||
|
||||
foreach my $c (@cases) |
||||
{ |
||||
test( |
||||
"hook misbehavior: $c->{'flag'}", |
||||
flags => [ $c->{'flag'} ], |
||||
expected_stderr => $c->{'expected_error'}); |
||||
} |
||||
|
||||
done_testing(); |
@ -0,0 +1,140 @@ |
||||
|
||||
# Copyright (c) 2025, PostgreSQL Global Development Group |
||||
|
||||
=pod |
||||
|
||||
=head1 NAME |
||||
|
||||
OAuth::Server - runs a mock OAuth authorization server for testing |
||||
|
||||
=head1 SYNOPSIS |
||||
|
||||
use OAuth::Server; |
||||
|
||||
my $server = OAuth::Server->new(); |
||||
$server->run; |
||||
|
||||
my $port = $server->port; |
||||
my $issuer = "http://localhost:$port"; |
||||
|
||||
# test against $issuer... |
||||
|
||||
$server->stop; |
||||
|
||||
=head1 DESCRIPTION |
||||
|
||||
This is glue API between the Perl tests and the Python authorization server |
||||
daemon implemented in t/oauth_server.py. (Python has a fairly usable HTTP server |
||||
in its standard library, so the implementation was ported from Perl.) |
||||
|
||||
This authorization server does not use TLS (it implements a nonstandard, unsafe |
||||
issuer at "http://localhost:<port>"), so libpq in particular will need to set |
||||
PGOAUTHDEBUG=UNSAFE to be able to talk to it. |
||||
|
||||
=cut |
||||
|
||||
package OAuth::Server; |
||||
|
||||
use warnings; |
||||
use strict; |
||||
use Scalar::Util; |
||||
use Test::More; |
||||
|
||||
=pod |
||||
|
||||
=head1 METHODS |
||||
|
||||
=over |
||||
|
||||
=item OAuth::Server->new() |
||||
|
||||
Create a new OAuth Server object. |
||||
|
||||
=cut |
||||
|
||||
sub new |
||||
{ |
||||
my $class = shift; |
||||
|
||||
my $self = {}; |
||||
bless($self, $class); |
||||
|
||||
return $self; |
||||
} |
||||
|
||||
=pod |
||||
|
||||
=item $server->port() |
||||
|
||||
Returns the port in use by the server. |
||||
|
||||
=cut |
||||
|
||||
sub port |
||||
{ |
||||
my $self = shift; |
||||
|
||||
return $self->{'port'}; |
||||
} |
||||
|
||||
=pod |
||||
|
||||
=item $server->run() |
||||
|
||||
Runs the authorization server daemon in t/oauth_server.py. |
||||
|
||||
=cut |
||||
|
||||
sub run |
||||
{ |
||||
my $self = shift; |
||||
my $port; |
||||
|
||||
my $pid = open(my $read_fh, "-|", $ENV{PYTHON}, "t/oauth_server.py") |
||||
or die "failed to start OAuth server: $!"; |
||||
|
||||
# Get the port number from the daemon. It closes stdout afterwards; that way |
||||
# we can slurp in the entire contents here rather than worrying about the |
||||
# number of bytes to read. |
||||
$port = do { local $/ = undef; <$read_fh> } |
||||
// die "failed to read port number: $!"; |
||||
chomp $port; |
||||
die "server did not advertise a valid port" |
||||
unless Scalar::Util::looks_like_number($port); |
||||
|
||||
$self->{'pid'} = $pid; |
||||
$self->{'port'} = $port; |
||||
$self->{'child'} = $read_fh; |
||||
|
||||
note("OAuth provider (PID $pid) is listening on port $port\n"); |
||||
} |
||||
|
||||
=pod |
||||
|
||||
=item $server->stop() |
||||
|
||||
Sends SIGTERM to the authorization server and waits for it to exit. |
||||
|
||||
=cut |
||||
|
||||
sub stop |
||||
{ |
||||
my $self = shift; |
||||
|
||||
note("Sending SIGTERM to OAuth provider PID: $self->{'pid'}\n"); |
||||
|
||||
kill(15, $self->{'pid'}); |
||||
$self->{'pid'} = undef; |
||||
|
||||
# Closing the popen() handle waits for the process to exit. |
||||
close($self->{'child'}); |
||||
$self->{'child'} = undef; |
||||
} |
||||
|
||||
=pod |
||||
|
||||
=back |
||||
|
||||
=cut |
||||
|
||||
1; |
@ -0,0 +1,391 @@ |
||||
#! /usr/bin/env python3 |
||||
# |
||||
# A mock OAuth authorization server, designed to be invoked from |
||||
# OAuth/Server.pm. This listens on an ephemeral port number (printed to stdout |
||||
# so that the Perl tests can contact it) and runs as a daemon until it is |
||||
# signaled. |
||||
# |
||||
|
||||
import base64 |
||||
import http.server |
||||
import json |
||||
import os |
||||
import sys |
||||
import time |
||||
import urllib.parse |
||||
from collections import defaultdict |
||||
|
||||
|
||||
class OAuthHandler(http.server.BaseHTTPRequestHandler): |
||||
""" |
||||
Core implementation of the authorization server. The API is |
||||
inheritance-based, with entry points at do_GET() and do_POST(). See the |
||||
documentation for BaseHTTPRequestHandler. |
||||
""" |
||||
|
||||
JsonObject = dict[str, object] # TypeAlias is not available until 3.10 |
||||
|
||||
def _check_issuer(self): |
||||
""" |
||||
Switches the behavior of the provider depending on the issuer URI. |
||||
""" |
||||
self._alt_issuer = ( |
||||
self.path.startswith("/alternate/") |
||||
or self.path == "/.well-known/oauth-authorization-server/alternate" |
||||
) |
||||
self._parameterized = self.path.startswith("/param/") |
||||
|
||||
if self._alt_issuer: |
||||
# The /alternate issuer uses IETF-style .well-known URIs. |
||||
if self.path.startswith("/.well-known/"): |
||||
self.path = self.path.removesuffix("/alternate") |
||||
else: |
||||
self.path = self.path.removeprefix("/alternate") |
||||
elif self._parameterized: |
||||
self.path = self.path.removeprefix("/param") |
||||
|
||||
def _check_authn(self): |
||||
""" |
||||
Checks the expected value of the Authorization header, if any. |
||||
""" |
||||
secret = self._get_param("expected_secret", None) |
||||
if secret is None: |
||||
return |
||||
|
||||
assert "Authorization" in self.headers |
||||
method, creds = self.headers["Authorization"].split() |
||||
|
||||
if method != "Basic": |
||||
raise RuntimeError(f"client used {method} auth; expected Basic") |
||||
|
||||
username = urllib.parse.quote_plus(self.client_id) |
||||
password = urllib.parse.quote_plus(secret) |
||||
expected_creds = f"{username}:{password}" |
||||
|
||||
if creds.encode() != base64.b64encode(expected_creds.encode()): |
||||
raise RuntimeError( |
||||
f"client sent '{creds}'; expected b64encode('{expected_creds}')" |
||||
) |
||||
|
||||
def do_GET(self): |
||||
self._response_code = 200 |
||||
self._check_issuer() |
||||
|
||||
config_path = "/.well-known/openid-configuration" |
||||
if self._alt_issuer: |
||||
config_path = "/.well-known/oauth-authorization-server" |
||||
|
||||
if self.path == config_path: |
||||
resp = self.config() |
||||
else: |
||||
self.send_error(404, "Not Found") |
||||
return |
||||
|
||||
self._send_json(resp) |
||||
|
||||
def _parse_params(self) -> dict[str, str]: |
||||
""" |
||||
Parses apart the form-urlencoded request body and returns the resulting |
||||
dict. For use by do_POST(). |
||||
""" |
||||
size = int(self.headers["Content-Length"]) |
||||
form = self.rfile.read(size) |
||||
|
||||
assert self.headers["Content-Type"] == "application/x-www-form-urlencoded" |
||||
return urllib.parse.parse_qs( |
||||
form.decode("utf-8"), |
||||
strict_parsing=True, |
||||
keep_blank_values=True, |
||||
encoding="utf-8", |
||||
errors="strict", |
||||
) |
||||
|
||||
@property |
||||
def client_id(self) -> str: |
||||
""" |
||||
Returns the client_id sent in the POST body or the Authorization header. |
||||
self._parse_params() must have been called first. |
||||
""" |
||||
if "client_id" in self._params: |
||||
return self._params["client_id"][0] |
||||
|
||||
if "Authorization" not in self.headers: |
||||
raise RuntimeError("client did not send any client_id") |
||||
|
||||
_, creds = self.headers["Authorization"].split() |
||||
|
||||
decoded = base64.b64decode(creds).decode("utf-8") |
||||
username, _ = decoded.split(":", 1) |
||||
|
||||
return urllib.parse.unquote_plus(username) |
||||
|
||||
def do_POST(self): |
||||
self._response_code = 200 |
||||
self._check_issuer() |
||||
|
||||
self._params = self._parse_params() |
||||
if self._parameterized: |
||||
# Pull encoded test parameters out of the peer's client_id field. |
||||
# This is expected to be Base64-encoded JSON. |
||||
js = base64.b64decode(self.client_id) |
||||
self._test_params = json.loads(js) |
||||
|
||||
self._check_authn() |
||||
|
||||
if self.path == "/authorize": |
||||
resp = self.authorization() |
||||
elif self.path == "/token": |
||||
resp = self.token() |
||||
else: |
||||
self.send_error(404) |
||||
return |
||||
|
||||
self._send_json(resp) |
||||
|
||||
def _should_modify(self) -> bool: |
||||
""" |
||||
Returns True if the client has requested a modification to this stage of |
||||
the exchange. |
||||
""" |
||||
if not hasattr(self, "_test_params"): |
||||
return False |
||||
|
||||
stage = self._test_params.get("stage") |
||||
|
||||
return ( |
||||
stage == "all" |
||||
or ( |
||||
stage == "discovery" |
||||
and self.path == "/.well-known/openid-configuration" |
||||
) |
||||
or (stage == "device" and self.path == "/authorize") |
||||
or (stage == "token" and self.path == "/token") |
||||
) |
||||
|
||||
def _get_param(self, name, default): |
||||
""" |
||||
If the client has requested a modification to this stage (see |
||||
_should_modify()), this method searches the provided test parameters for |
||||
a key of the given name, and returns it if found. Otherwise the provided |
||||
default is returned. |
||||
""" |
||||
if self._should_modify() and name in self._test_params: |
||||
return self._test_params[name] |
||||
|
||||
return default |
||||
|
||||
@property |
||||
def _content_type(self) -> str: |
||||
""" |
||||
Returns "application/json" unless the test has requested something |
||||
different. |
||||
""" |
||||
return self._get_param("content_type", "application/json") |
||||
|
||||
@property |
||||
def _interval(self) -> int: |
||||
""" |
||||
Returns 0 unless the test has requested something different. |
||||
""" |
||||
return self._get_param("interval", 0) |
||||
|
||||
@property |
||||
def _retry_code(self) -> str: |
||||
""" |
||||
Returns "authorization_pending" unless the test has requested something |
||||
different. |
||||
""" |
||||
return self._get_param("retry_code", "authorization_pending") |
||||
|
||||
@property |
||||
def _uri_spelling(self) -> str: |
||||
""" |
||||
Returns "verification_uri" unless the test has requested something |
||||
different. |
||||
""" |
||||
return self._get_param("uri_spelling", "verification_uri") |
||||
|
||||
@property |
||||
def _response_padding(self): |
||||
""" |
||||
If the huge_response test parameter is set to True, returns a dict |
||||
containing a gigantic string value, which can then be folded into a JSON |
||||
response. |
||||
""" |
||||
if not self._get_param("huge_response", False): |
||||
return dict() |
||||
|
||||
return {"_pad_": "x" * 1024 * 1024} |
||||
|
||||
@property |
||||
def _access_token(self): |
||||
""" |
||||
The actual Bearer token sent back to the client on success. Tests may |
||||
override this with the "token" test parameter. |
||||
""" |
||||
token = self._get_param("token", None) |
||||
if token is not None: |
||||
return token |
||||
|
||||
token = "9243959234" |
||||
if self._alt_issuer: |
||||
token += "-alt" |
||||
|
||||
return token |
||||
|
||||
def _send_json(self, js: JsonObject) -> None: |
||||
""" |
||||
Sends the provided JSON dict as an application/json response. |
||||
self._response_code can be modified to send JSON error responses. |
||||
""" |
||||
resp = json.dumps(js).encode("ascii") |
||||
self.log_message("sending JSON response: %s", resp) |
||||
|
||||
self.send_response(self._response_code) |
||||
self.send_header("Content-Type", self._content_type) |
||||
self.send_header("Content-Length", str(len(resp))) |
||||
self.end_headers() |
||||
|
||||
self.wfile.write(resp) |
||||
|
||||
def config(self) -> JsonObject: |
||||
port = self.server.socket.getsockname()[1] |
||||
|
||||
issuer = f"http://localhost:{port}" |
||||
if self._alt_issuer: |
||||
issuer += "/alternate" |
||||
elif self._parameterized: |
||||
issuer += "/param" |
||||
|
||||
return { |
||||
"issuer": issuer, |
||||
"token_endpoint": issuer + "/token", |
||||
"device_authorization_endpoint": issuer + "/authorize", |
||||
"response_types_supported": ["token"], |
||||
"subject_types_supported": ["public"], |
||||
"id_token_signing_alg_values_supported": ["RS256"], |
||||
"grant_types_supported": [ |
||||
"authorization_code", |
||||
"urn:ietf:params:oauth:grant-type:device_code", |
||||
], |
||||
} |
||||
|
||||
@property |
||||
def _token_state(self): |
||||
""" |
||||
A cached _TokenState object for the connected client (as determined by |
||||
the request's client_id), or a new one if it doesn't already exist. |
||||
|
||||
This relies on the existence of a defaultdict attached to the server; |
||||
see main() below. |
||||
""" |
||||
return self.server.token_state[self.client_id] |
||||
|
||||
def _remove_token_state(self): |
||||
""" |
||||
Removes any cached _TokenState for the current client_id. Call this |
||||
after the token exchange ends to get rid of unnecessary state. |
||||
""" |
||||
if self.client_id in self.server.token_state: |
||||
del self.server.token_state[self.client_id] |
||||
|
||||
def authorization(self) -> JsonObject: |
||||
uri = "https://example.com/" |
||||
if self._alt_issuer: |
||||
uri = "https://example.org/" |
||||
|
||||
resp = { |
||||
"device_code": "postgres", |
||||
"user_code": "postgresuser", |
||||
self._uri_spelling: uri, |
||||
"expires_in": 5, |
||||
**self._response_padding, |
||||
} |
||||
|
||||
interval = self._interval |
||||
if interval is not None: |
||||
resp["interval"] = interval |
||||
self._token_state.min_delay = interval |
||||
else: |
||||
self._token_state.min_delay = 5 # default |
||||
|
||||
# Check the scope. |
||||
if "scope" in self._params: |
||||
assert self._params["scope"][0], "empty scopes should be omitted" |
||||
|
||||
return resp |
||||
|
||||
def token(self) -> JsonObject: |
||||
if err := self._get_param("error_code", None): |
||||
self._response_code = self._get_param("error_status", 400) |
||||
|
||||
resp = {"error": err} |
||||
if desc := self._get_param("error_desc", ""): |
||||
resp["error_description"] = desc |
||||
|
||||
return resp |
||||
|
||||
if self._should_modify() and "retries" in self._test_params: |
||||
retries = self._test_params["retries"] |
||||
|
||||
# Check to make sure the token interval is being respected. |
||||
now = time.monotonic() |
||||
if self._token_state.last_try is not None: |
||||
delay = now - self._token_state.last_try |
||||
assert ( |
||||
delay > self._token_state.min_delay |
||||
), f"client waited only {delay} seconds between token requests (expected {self._token_state.min_delay})" |
||||
|
||||
self._token_state.last_try = now |
||||
|
||||
# If we haven't reached the required number of retries yet, return a |
||||
# "pending" response. |
||||
if self._token_state.retries < retries: |
||||
self._token_state.retries += 1 |
||||
|
||||
self._response_code = 400 |
||||
return {"error": self._retry_code} |
||||
|
||||
# Clean up any retry tracking state now that the exchange is ending. |
||||
self._remove_token_state() |
||||
|
||||
return { |
||||
"access_token": self._access_token, |
||||
"token_type": "bearer", |
||||
**self._response_padding, |
||||
} |
||||
|
||||
|
||||
def main(): |
||||
""" |
||||
Starts the authorization server on localhost. The ephemeral port in use will |
||||
be printed to stdout. |
||||
""" |
||||
|
||||
s = http.server.HTTPServer(("127.0.0.1", 0), OAuthHandler) |
||||
|
||||
# Attach a "cache" dictionary to the server to allow the OAuthHandlers to |
||||
# track state across token requests. The use of defaultdict ensures that new |
||||
# entries will be created automatically. |
||||
class _TokenState: |
||||
retries = 0 |
||||
min_delay = None |
||||
last_try = None |
||||
|
||||
s.token_state = defaultdict(_TokenState) |
||||
|
||||
# Give the parent the port number to contact (this is also the signal that |
||||
# we're ready to receive requests). |
||||
port = s.socket.getsockname()[1] |
||||
print(port) |
||||
|
||||
# stdout is closed to allow the parent to just "read to the end". |
||||
stdout = sys.stdout.fileno() |
||||
sys.stdout.close() |
||||
os.close(stdout) |
||||
|
||||
s.serve_forever() # we expect our parent to send a termination signal |
||||
|
||||
|
||||
if __name__ == "__main__": |
||||
main() |
@ -0,0 +1,143 @@ |
||||
/*-------------------------------------------------------------------------
|
||||
* |
||||
* validator.c |
||||
* Test module for serverside OAuth token validation callbacks |
||||
* |
||||
* Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group |
||||
* Portions Copyright (c) 1994, Regents of the University of California |
||||
* |
||||
* src/test/modules/oauth_validator/validator.c |
||||
* |
||||
*------------------------------------------------------------------------- |
||||
*/ |
||||
|
||||
#include "postgres.h" |
||||
|
||||
#include "fmgr.h" |
||||
#include "libpq/oauth.h" |
||||
#include "miscadmin.h" |
||||
#include "utils/guc.h" |
||||
#include "utils/memutils.h" |
||||
|
||||
PG_MODULE_MAGIC; |
||||
|
||||
static void validator_startup(ValidatorModuleState *state); |
||||
static void validator_shutdown(ValidatorModuleState *state); |
||||
static bool validate_token(const ValidatorModuleState *state, |
||||
const char *token, |
||||
const char *role, |
||||
ValidatorModuleResult *result); |
||||
|
||||
/* Callback implementations (exercise all three) */ |
||||
static const OAuthValidatorCallbacks validator_callbacks = { |
||||
PG_OAUTH_VALIDATOR_MAGIC, |
||||
|
||||
.startup_cb = validator_startup, |
||||
.shutdown_cb = validator_shutdown, |
||||
.validate_cb = validate_token |
||||
}; |
||||
|
||||
/* GUCs */ |
||||
static char *authn_id = NULL; |
||||
static bool authorize_tokens = true; |
||||
|
||||
/*---
|
||||
* Extension entry point. Sets up GUCs for use by tests: |
||||
* |
||||
* - oauth_validator.authn_id Sets the user identifier to return during token |
||||
* validation. Defaults to the username in the |
||||
* startup packet. |
||||
* |
||||
* - oauth_validator.authorize_tokens |
||||
* Sets whether to successfully validate incoming |
||||
* tokens. Defaults to true. |
||||
*/ |
||||
void |
||||
_PG_init(void) |
||||
{ |
||||
DefineCustomStringVariable("oauth_validator.authn_id", |
||||
"Authenticated identity to use for future connections", |
||||
NULL, |
||||
&authn_id, |
||||
NULL, |
||||
PGC_SIGHUP, |
||||
0, |
||||
NULL, NULL, NULL); |
||||
DefineCustomBoolVariable("oauth_validator.authorize_tokens", |
||||
"Should tokens be marked valid?", |
||||
NULL, |
||||
&authorize_tokens, |
||||
true, |
||||
PGC_SIGHUP, |
||||
0, |
||||
NULL, NULL, NULL); |
||||
|
||||
MarkGUCPrefixReserved("oauth_validator"); |
||||
} |
||||
|
||||
/*
|
||||
* Validator module entry point. |
||||
*/ |
||||
const OAuthValidatorCallbacks * |
||||
_PG_oauth_validator_module_init(void) |
||||
{ |
||||
return &validator_callbacks; |
||||
} |
||||
|
||||
#define PRIVATE_COOKIE ((void *) 13579) |
||||
|
||||
/*
|
||||
* Startup callback, to set up private data for the validator. |
||||
*/ |
||||
static void |
||||
validator_startup(ValidatorModuleState *state) |
||||
{ |
||||
/*
|
||||
* Make sure the server is correctly setting sversion. (Real modules |
||||
* should not do this; it would defeat upgrade compatibility.) |
||||
*/ |
||||
if (state->sversion != PG_VERSION_NUM) |
||||
elog(ERROR, "oauth_validator: sversion set to %d", state->sversion); |
||||
|
||||
state->private_data = PRIVATE_COOKIE; |
||||
} |
||||
|
||||
/*
|
||||
* Shutdown callback, to tear down the validator. |
||||
*/ |
||||
static void |
||||
validator_shutdown(ValidatorModuleState *state) |
||||
{ |
||||
/* Check to make sure our private state still exists. */ |
||||
if (state->private_data != PRIVATE_COOKIE) |
||||
elog(PANIC, "oauth_validator: private state cookie changed to %p in shutdown", |
||||
state->private_data); |
||||
} |
||||
|
||||
/*
|
||||
* Validator implementation. Logs the incoming data and authorizes the token by |
||||
* default; the behavior can be modified via the module's GUC settings. |
||||
*/ |
||||
static bool |
||||
validate_token(const ValidatorModuleState *state, |
||||
const char *token, const char *role, |
||||
ValidatorModuleResult *res) |
||||
{ |
||||
/* Check to make sure our private state still exists. */ |
||||
if (state->private_data != PRIVATE_COOKIE) |
||||
elog(ERROR, "oauth_validator: private state cookie changed to %p in validate", |
||||
state->private_data); |
||||
|
||||
elog(LOG, "oauth_validator: token=\"%s\", role=\"%s\"", token, role); |
||||
elog(LOG, "oauth_validator: issuer=\"%s\", scope=\"%s\"", |
||||
MyProcPort->hba->oauth_issuer, |
||||
MyProcPort->hba->oauth_scope); |
||||
|
||||
res->authorized = authorize_tokens; |
||||
if (authn_id) |
||||
res->authn_id = pstrdup(authn_id); |
||||
else |
||||
res->authn_id = pstrdup(role); |
||||
|
||||
return true; |
||||
} |
Loading…
Reference in new issue