Debian Codegraph @

doc/src/sgml/oauth-validators.sgml

raw
1 <!-- doc/src/sgml/oauth-validators.sgml -->
2
3 <chapter id="oauth-validators">
4 <title>OAuth Validator Modules</title>
5 <indexterm zone="oauth-validators">
6 <primary>OAuth Validators</primary>
7 </indexterm>
8 <para>
9 <productname>PostgreSQL</productname> provides infrastructure for creating
10 custom modules to perform server-side validation of OAuth bearer tokens.
11 Because OAuth implementations vary so wildly, and bearer token validation is
12 heavily dependent on the issuing party, the server cannot check the token
13 itself; validator modules provide the integration layer between the server
14 and the OAuth provider in use.
15 </para>
16 <para>
17 OAuth validator modules must at least consist of an initialization function
18 (see <xref linkend="oauth-validator-init"/>) and the required callback for
19 performing validation (see <xref linkend="oauth-validator-callback-validate"/>).
20 </para>
21 <warning>
22 <para>
23 Since a misbehaving validator might let unauthorized users into the database,
24 correct implementation is crucial for server safety. See
25 <xref linkend="oauth-validator-design"/> for design considerations.
26 </para>
27 </warning>
28
29 <sect1 id="oauth-validator-design">
30 <title>Safely Designing a Validator Module</title>
31 <warning>
32 <para>
33 Read and understand the entirety of this section before implementing a
34 validator module. A malfunctioning validator is potentially worse than no
35 authentication at all, both because of the false sense of security it
36 provides, and because it may contribute to attacks against other pieces of
37 an OAuth ecosystem.
38 </para>
39 </warning>
40
41 <sect2 id="oauth-validator-design-responsibilities">
42 <title>Validator Responsibilities</title>
43 <para>
44 Although different modules may take very different approaches to token
45 validation, implementations generally need to perform three separate
46 actions:
47 </para>
48 <variablelist>
49 <varlistentry>
50 <term>Validate the Token</term>
51 <listitem>
52 <para>
53 The validator must first ensure that the presented token is in fact a
54 valid Bearer token for use in client authentication. The correct way to
55 do this depends on the provider, but it generally involves either
56 cryptographic operations to prove that the token was created by a trusted
57 party (offline validation), or the presentation of the token to that
58 trusted party so that it can perform validation for you (online
59 validation).
60 </para>
61 <para>
62 Online validation, usually implemented via
63 <ulink url="https://datatracker.ietf.org/doc/html/rfc7662">OAuth Token
64 Introspection</ulink>, requires fewer steps of a validator module and
65 allows central revocation of a token in the event that it is stolen
66 or misissued. However, it does require the module to make at least one
67 network call per authentication attempt (all of which must complete
68 within the configured <xref linkend="guc-authentication-timeout"/>).
69 Additionally, your provider may not provide introspection endpoints for
70 use by external resource servers.
71 </para>
72 <para>
73 Offline validation is much more involved, typically requiring a validator
74 to maintain a list of trusted signing keys for a provider and then
75 check the token's cryptographic signature along with its contents.
76 Implementations must follow the provider's instructions to the letter,
77 including any verification of issuer ("where is this token from?"),
78 audience ("who is this token for?"), and validity period ("when can this
79 token be used?"). Since there is no communication between the module and
80 the provider, tokens cannot be centrally revoked using this method;
81 offline validator implementations may wish to place restrictions on the
82 maximum length of a token's validity period.
83 </para>
84 <para>
85 If the token cannot be validated, the module should immediately fail.
86 Further authentication/authorization is pointless if the bearer token
87 wasn't issued by a trusted party.
88 </para>
89 </listitem>
90 </varlistentry>
91 <varlistentry>
92 <term>Authorize the Client</term>
93 <listitem>
94 <para>
95 Next the validator must ensure that the end user has given the client
96 permission to access the server on their behalf. This generally involves
97 checking the scopes that have been assigned to the token, to make sure
98 that they cover database access for the current HBA parameters.
99 </para>
100 <para>
101 The purpose of this step is to prevent an OAuth client from obtaining a
102 token under false pretenses. If the validator requires all tokens to
103 carry scopes that cover database access, the provider should then loudly
104 prompt the user to grant that access during the flow. This gives them the
105 opportunity to reject the request if the client isn't supposed to be
106 using their credentials to connect to databases.
107 </para>
108 <para>
109 While it is possible to establish client authorization without explicit
110 scopes by using out-of-band knowledge of the deployed architecture, doing
111 so removes the user from the loop, which prevents them from catching
112 deployment mistakes and allows any such mistakes to be exploited
113 silently. Access to the database must be tightly restricted to only
114 trusted clients
115 <footnote>
116 <para>
117 That is, "trusted" in the sense that the OAuth client and the
118 <productname>PostgreSQL</productname> server are controlled by the same
119 entity. Notably, the Device Authorization client flow supported by
120 libpq does not usually meet this bar, since it's designed for use by
121 public/untrusted clients.
122 </para>
123 </footnote>
124 if users are not prompted for additional scopes.
125 </para>
126 <para>
127 Even if authorization fails, a module may choose to continue to pull
128 authentication information from the token for use in auditing and
129 debugging.
130 </para>
131 </listitem>
132 </varlistentry>
133 <varlistentry>
134 <term>Authenticate the End User</term>
135 <listitem>
136 <para>
137 Finally, the validator should determine a user identifier for the token,
138 either by asking the provider for this information or by extracting it
139 from the token itself, and return that identifier to the server (which
140 will then make a final authorization decision using the HBA
141 configuration). This identifier will be available within the session via
142 <link linkend="functions-info-session-table"><function>system_user</function></link>
143 and recorded in the server logs if <xref linkend="guc-log-connections"/>
144 is enabled.
145 </para>
146 <para>
147 Different providers may record a variety of different authentication
148 information for an end user, typically referred to as
149 <emphasis>claims</emphasis>. Providers usually document which of these
150 claims are trustworthy enough to use for authorization decisions and
151 which are not. (For instance, it would probably not be wise to use an
152 end user's full name as the identifier for authentication, since many
153 providers allow users to change their display names arbitrarily.)
154 Ultimately, the choice of which claim (or combination of claims) to use
155 comes down to the provider implementation and application requirements.
156 </para>
157 <para>
158 Note that anonymous/pseudonymous login is possible as well, by enabling
159 usermap delegation; see
160 <xref linkend="oauth-validator-design-usermap-delegation"/>.
161 </para>
162 </listitem>
163 </varlistentry>
164 </variablelist>
165 </sect2>
166
167 <sect2 id="oauth-validator-design-guidelines">
168 <title>General Coding Guidelines</title>
169 <para>
170 Developers should keep the following in mind when implementing token
171 validation:
172 </para>
173 <variablelist>
174 <varlistentry>
175 <term>Token Confidentiality</term>
176 <listitem>
177 <para>
178 Modules should not write tokens, or pieces of tokens, into the server
179 log. This is true even if the module considers the token invalid; an
180 attacker who confuses a client into communicating with the wrong provider
181 should not be able to retrieve that (otherwise valid) token from the
182 disk.
183 </para>
184 <para>
185 Implementations that send tokens over the network (for example, to
186 perform online token validation with a provider) must authenticate the
187 peer and ensure that strong transport security is in use.
188 </para>
189 </listitem>
190 </varlistentry>
191 <varlistentry>
192 <term>Logging</term>
193 <listitem>
194 <para>
195 Modules may use the same <link linkend="error-message-reporting">logging
196 facilities</link> as standard extensions; however, the rules for emitting
197 log entries to the client are subtly different during the authentication
198 phase of the connection. Generally speaking, modules should log
199 verification problems at the <symbol>COMMERROR</symbol> level and return
200 normally, instead of using <symbol>ERROR</symbol>/<symbol>FATAL</symbol>
201 to unwind the stack, to avoid leaking information to unauthenticated
202 clients.
203 </para>
204 </listitem>
205 </varlistentry>
206 <varlistentry>
207 <term>Interruptibility</term>
208 <listitem>
209 <para>
210 Modules must remain interruptible by signals so that the server can
211 correctly handle authentication timeouts and shutdown signals from
212 <application>pg_ctl</application>. For example, blocking calls on sockets
213 should generally be replaced with code that handles both socket events
214 and interrupts without races (see <function>WaitLatchOrSocket()</function>,
215 <function>WaitEventSetWait()</function>, et al), and long-running loops
216 should periodically call <function>CHECK_FOR_INTERRUPTS()</function>.
217 Failure to follow this guidance may result in unresponsive backend
218 sessions.
219 </para>
220 </listitem>
221 </varlistentry>
222 <varlistentry>
223 <term>Testing</term>
224 <listitem>
225 <para>
226 The breadth of testing an OAuth system is well beyond the scope of this
227 documentation, but at minimum, negative testing should be considered
228 mandatory. It's trivial to design a module that lets authorized users in;
229 the whole point of the system is to keep unauthorized users out.
230 </para>
231 </listitem>
232 </varlistentry>
233 <varlistentry>
234 <term>Documentation</term>
235 <listitem>
236 <para>
237 Validator implementations should document the contents and format of the
238 authenticated ID that is reported to the server for each end user, since
239 DBAs may need to use this information to construct pg_ident maps. (For
240 instance, is it an email address? an organizational ID number? a UUID?)
241 They should also document whether or not it is safe to use the module in
242 <symbol>delegate_ident_mapping=1</symbol> mode, and what additional
243 configuration is required in order to do so.
244 </para>
245 </listitem>
246 </varlistentry>
247 </variablelist>
248 </sect2>
249
250 <sect2 id="oauth-validator-design-usermap-delegation">
251 <title>Authorizing Users (Usermap Delegation)</title>
252 <para>
253 The standard deliverable of a validation module is the user identifier,
254 which the server will then compare to any configured
255 <link linkend="auth-username-maps"><filename>pg_ident.conf</filename>
256 mappings</link> and determine whether the end user is authorized to connect.
257 However, OAuth is itself an authorization framework, and tokens may carry
258 information about user privileges. For example, a token may be associated
259 with the organizational groups that a user belongs to, or list the roles
260 that a user may assume, and duplicating that knowledge into local usermaps
261 for every server may not be desirable.
262 </para>
263 <para>
264 To bypass username mapping entirely, and have the validator module assume
265 the additional responsibility of authorizing user connections, the HBA may
266 be configured with <xref linkend="auth-oauth-delegate-ident-mapping"/>.
267 The module may then use token scopes or an equivalent method to decide
268 whether the user is allowed to connect under their desired role. The user
269 identifier will still be recorded by the server, but it plays no part in
270 determining whether to continue the connection.
271 </para>
272 <para>
273 Using this scheme, authentication itself is optional. As long as the module
274 reports that the connection is authorized, login will continue even if there
275 is no recorded user identifier at all. This makes it possible to implement
276 anonymous or pseudonymous access to the database, where the third-party
277 provider performs all necessary authentication but does not provide any
278 user-identifying information to the server. (Some providers may create an
279 anonymized ID number that can be recorded instead, for later auditing.)
280 </para>
281 <para>
282 Usermap delegation provides the most architectural flexibility, but it turns
283 the validator module into a single point of failure for connection
284 authorization. Use with caution.
285 </para>
286 </sect2>
287 </sect1>
288
289 <sect1 id="oauth-validator-init">
290 <title>Initialization Functions</title>
291 <indexterm zone="oauth-validator-init">
292 <primary>_PG_oauth_validator_module_init</primary>
293 </indexterm>
294 <para>
295 OAuth validator modules are dynamically loaded from the shared
296 libraries listed in <xref linkend="guc-oauth-validator-libraries"/>.
297 Modules are loaded on demand when requested from a login in progress.
298 The normal library search path is used to locate the library. To
299 provide the validator callbacks and to indicate that the library is an OAuth
300 validator module a function named
301 <function>_PG_oauth_validator_module_init</function> must be provided. The
302 return value of the function must be a pointer to a struct of type
303 <structname>OAuthValidatorCallbacks</structname>, which contains a magic
304 number and pointers to the module's token validation functions. The returned
305 pointer must be of server lifetime, which is typically achieved by defining
306 it as a <literal>static const</literal> variable in global scope.
307 <programlisting>
308 typedef struct OAuthValidatorCallbacks
309 {
310 uint32 magic; /* must be set to PG_OAUTH_VALIDATOR_MAGIC */
311
312 ValidatorStartupCB startup_cb;
313 ValidatorShutdownCB shutdown_cb;
314 ValidatorValidateCB validate_cb;
315 } OAuthValidatorCallbacks;
316
317 typedef const OAuthValidatorCallbacks *(*OAuthValidatorModuleInit) (void);
318 </programlisting>
319
320 Only the <function>validate_cb</function> callback is required, the others
321 are optional.
322 </para>
323 </sect1>
324
325 <sect1 id="oauth-validator-callbacks">
326 <title>OAuth Validator Callbacks</title>
327 <para>
328 OAuth validator modules implement their functionality by defining a set of
329 callbacks. The server will call them as required to process the
330 authentication request from the user.
331 </para>
332
333 <sect2 id="oauth-validator-callback-startup">
334 <title>Startup Callback</title>
335 <para>
336 The <function>startup_cb</function> callback is executed directly after
337 loading the module. This callback can be used to set up local state and
338 perform additional initialization if required. If the validator module
339 has state it can use <structfield>state->private_data</structfield> to
340 store it.
341
342 <programlisting>
343 typedef void (*ValidatorStartupCB) (ValidatorModuleState *state);
344 </programlisting>
345 </para>
346 </sect2>
347
348 <sect2 id="oauth-validator-callback-validate">
349 <title>Validate Callback</title>
350 <para>
351 The <function>validate_cb</function> callback is executed during the OAuth
352 exchange when a user attempts to authenticate using OAuth. Any state set in
353 previous calls will be available in <structfield>state->private_data</structfield>.
354
355 <programlisting>
356 typedef bool (*ValidatorValidateCB) (const ValidatorModuleState *state,
357 const char *token, const char *role,
358 ValidatorModuleResult *result);
359 </programlisting>
360
361 <replaceable>token</replaceable> will contain the bearer token to validate.
362 <application>PostgreSQL</application> has ensured that the token is well-formed syntactically, but no
363 other validation has been performed. <replaceable>role</replaceable> will
364 contain the role the user has requested to log in as. The callback must
365 set output parameters in the <literal>result</literal> struct, which is
366 defined as below:
367
368 <programlisting>
369 typedef struct ValidatorModuleResult
370 {
371 bool authorized;
372 char *authn_id;
373 } ValidatorModuleResult;
374 </programlisting>
375
376 The connection will only proceed if the module sets
377 <structfield>result->authorized</structfield> to <literal>true</literal>. To
378 authenticate the user, the authenticated user name (as determined using the
379 token) shall be palloc'd and returned in the <structfield>result->authn_id</structfield>
380 field. Alternatively, <structfield>result->authn_id</structfield> may be set to
381 NULL if the token is valid but the associated user identity cannot be
382 determined.
383 </para>
384 <para>
385 A validator may return <literal>false</literal> to signal an internal error,
386 in which case any result parameters are ignored and the connection fails.
387 Otherwise the validator should return <literal>true</literal> to indicate
388 that it has processed the token and made an authorization decision.
389 </para>
390 <para>
391 The behavior after <function>validate_cb</function> returns depends on the
392 specific HBA setup. Normally, the <structfield>result->authn_id</structfield> user
393 name must exactly match the role that the user is logging in as. (This
394 behavior may be modified with a usermap.) But when authenticating against
395 an HBA rule with <literal>delegate_ident_mapping</literal> turned on,
396 <productname>PostgreSQL</productname> will not perform any checks on the value of
397 <structfield>result->authn_id</structfield> at all; in this case it is up to the
398 validator to ensure that the token carries enough privileges for the user to
399 log in under the indicated <replaceable>role</replaceable>.
400 </para>
401 </sect2>
402
403 <sect2 id="oauth-validator-callback-shutdown">
404 <title>Shutdown Callback</title>
405 <para>
406 The <function>shutdown_cb</function> callback is executed when the server
407 backend has finished validating tokens for the connection. If the validator
408 module has any allocated state, this callback should free it to avoid
409 resource leaks.
410 <programlisting>
411 typedef void (*ValidatorShutdownCB) (ValidatorModuleState *state);
412 </programlisting>
413 </para>
414 </sect2>
415
416 </sect1>
417 </chapter>