Debian Codegraph @

src/interfaces/libpq-oauth/oauth-curl.c

raw
1 /*-------------------------------------------------------------------------
2 *
3 * oauth-curl.c
4 * The libcurl implementation of OAuth/OIDC authentication, using the
5 * OAuth Device Authorization Grant (RFC 8628).
6 *
7 * Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group
8 * Portions Copyright (c) 1994, Regents of the University of California
9 *
10 * IDENTIFICATION
11 * src/interfaces/libpq-oauth/oauth-curl.c
12 *
13 *-------------------------------------------------------------------------
14 */
15
16 #include "postgres_fe.h"
17
18 #include <curl/curl.h>
19 #include <math.h>
20 #include <unistd.h>
21
22 #if defined(HAVE_SYS_EPOLL_H)
23 #include <sys/epoll.h>
24 #include <sys/timerfd.h>
25 #elif defined(HAVE_SYS_EVENT_H)
26 #include <sys/event.h>
27 #else
28 #error libpq-oauth is not supported on this platform
29 #endif
30
31 #include "common/int.h"
32 #include "common/jsonapi.h"
33 #include "fe-auth-oauth.h"
34 #include "mb/pg_wchar.h"
35 #include "oauth-curl.h"
36
37 #ifdef USE_DYNAMIC_OAUTH
38
39 /*
40 * The module build is decoupled from libpq-int.h, to try to avoid inadvertent
41 * ABI breaks during minor version bumps. Replacements for the missing internals
42 * are provided by oauth-utils.
43 */
44 #include "oauth-utils.h"
45
46 #else /* !USE_DYNAMIC_OAUTH */
47
48 /*
49 * Static builds may rely on PGconn offsets directly. Keep these aligned with
50 * the bank of callbacks in oauth-utils.h.
51 */
52 #include "libpq-int.h"
53
54 #define conn_errorMessage(CONN) (&CONN->errorMessage)
55 #define conn_oauth_client_id(CONN) (CONN->oauth_client_id)
56 #define conn_oauth_client_secret(CONN) (CONN->oauth_client_secret)
57 #define conn_oauth_discovery_uri(CONN) (CONN->oauth_discovery_uri)
58 #define conn_oauth_issuer_id(CONN) (CONN->oauth_issuer_id)
59 #define conn_oauth_scope(CONN) (CONN->oauth_scope)
60 #define conn_sasl_state(CONN) (CONN->sasl_state)
61
62 #define set_conn_altsock(CONN, VAL) do { CONN->altsock = VAL; } while (0)
63 #define set_conn_oauth_token(CONN, VAL) do { CONN->oauth_token = VAL; } while (0)
64
65 #endif /* USE_DYNAMIC_OAUTH */
66
67 /* One final guardrail against accidental inclusion... */
68 #if defined(USE_DYNAMIC_OAUTH) && defined(LIBPQ_INT_H)
69 #error do not rely on libpq-int.h in dynamic builds of libpq-oauth
70 #endif
71
72 /*
73 * It's generally prudent to set a maximum response size to buffer in memory,
74 * but it's less clear what size to choose. The biggest of our expected
75 * responses is the server metadata JSON, which will only continue to grow in
76 * size; the number of IANA-registered parameters in that document is up to 78
77 * as of February 2025.
78 *
79 * Even if every single parameter were to take up 2k on average (a previously
80 * common limit on the size of a URL), 256k gives us 128 parameter values before
81 * we give up. (That's almost certainly complete overkill in practice; 2-4k
82 * appears to be common among popular providers at the moment.)
83 */
84 #define MAX_OAUTH_RESPONSE_SIZE (256 * 1024)
85
86 /*
87 * Similarly, a limit on the maximum JSON nesting level keeps a server from
88 * running us out of stack space. A common nesting level in practice is 2 (for a
89 * top-level object containing arrays of strings). As of May 2025, the maximum
90 * depth for standard server metadata appears to be 6, if the document contains
91 * a full JSON Web Key Set in its "jwks" parameter.
92 *
93 * Since it's easy to nest JSON, and the number of parameters and key types
94 * keeps growing, take a healthy buffer of 16. (If this ever proves to be a
95 * problem in practice, we may want to switch over to the incremental JSON
96 * parser instead of playing with this parameter.)
97 */
98 #define MAX_OAUTH_NESTING_LEVEL 16
99
100 /*
101 * Parsed JSON Representations
102 *
103 * As a general rule, we parse and cache only the fields we're currently using.
104 * When adding new fields, ensure the corresponding free_*() function is updated
105 * too.
106 */
107
108 /*
109 * The OpenID Provider configuration (alternatively named "authorization server
110 * metadata") jointly described by OpenID Connect Discovery 1.0 and RFC 8414:
111 *
112 * https://openid.net/specs/openid-connect-discovery-1_0.html
113 * https://www.rfc-editor.org/rfc/rfc8414#section-3.2
114 */
115 struct provider
116 {
117 char *issuer;
118 char *token_endpoint;
119 char *device_authorization_endpoint;
120 struct curl_slist *grant_types_supported;
121 };
122
123 static void
124 free_provider(struct provider *provider)
125 {
126 free(provider->issuer);
127 free(provider->token_endpoint);
128 free(provider->device_authorization_endpoint);
129 curl_slist_free_all(provider->grant_types_supported);
130 }
131
132 /*
133 * The Device Authorization response, described by RFC 8628:
134 *
135 * https://www.rfc-editor.org/rfc/rfc8628#section-3.2
136 */
137 struct device_authz
138 {
139 char *device_code;
140 char *user_code;
141 char *verification_uri;
142 char *verification_uri_complete;
143 char *expires_in_str;
144 char *interval_str;
145
146 /* Fields below are parsed from the corresponding string above. */
147 int expires_in;
148 int32 interval;
149 };
150
151 static void
152 free_device_authz(struct device_authz *authz)
153 {
154 free(authz->device_code);
155 free(authz->user_code);
156 free(authz->verification_uri);
157 free(authz->verification_uri_complete);
158 free(authz->expires_in_str);
159 free(authz->interval_str);
160 }
161
162 /*
163 * The Token Endpoint error response, as described by RFC 6749:
164 *
165 * https://www.rfc-editor.org/rfc/rfc6749#section-5.2
166 *
167 * Note that this response type can also be returned from the Device
168 * Authorization Endpoint.
169 */
170 struct token_error
171 {
172 char *error;
173 char *error_description;
174 };
175
176 static void
177 free_token_error(struct token_error *err)
178 {
179 free(err->error);
180 free(err->error_description);
181 }
182
183 /*
184 * The Access Token response, as described by RFC 6749:
185 *
186 * https://www.rfc-editor.org/rfc/rfc6749#section-4.1.4
187 *
188 * During the Device Authorization flow, several temporary errors are expected
189 * as part of normal operation. To make it easy to handle these in the happy
190 * path, this contains an embedded token_error that is filled in if needed.
191 */
192 struct token
193 {
194 /* for successful responses */
195 char *access_token;
196 char *token_type;
197
198 /* for error responses */
199 struct token_error err;
200 };
201
202 static void
203 free_token(struct token *tok)
204 {
205 free(tok->access_token);
206 free(tok->token_type);
207 free_token_error(&tok->err);
208 }
209
210 /*
211 * Asynchronous State
212 */
213
214 /* States for the overall async machine. */
215 enum OAuthStep
216 {
217 OAUTH_STEP_INIT = 0,
218 OAUTH_STEP_DISCOVERY,
219 OAUTH_STEP_DEVICE_AUTHORIZATION,
220 OAUTH_STEP_TOKEN_REQUEST,
221 OAUTH_STEP_WAIT_INTERVAL,
222 };
223
224 /*
225 * The async_ctx holds onto state that needs to persist across multiple calls
226 * to pg_fe_run_oauth_flow(). Almost everything interacts with this in some
227 * way.
228 */
229 struct async_ctx
230 {
231 enum OAuthStep step; /* where are we in the flow? */
232
233 int timerfd; /* descriptor for signaling async timeouts */
234 pgsocket mux; /* the multiplexer socket containing all
235 * descriptors tracked by libcurl, plus the
236 * timerfd */
237 CURLM *curlm; /* top-level multi handle for libcurl
238 * operations */
239 CURL *curl; /* the (single) easy handle for serial
240 * requests */
241
242 struct curl_slist *headers; /* common headers for all requests */
243 PQExpBufferData work_data; /* scratch buffer for general use (remember to
244 * clear out prior contents first!) */
245
246 /*------
247 * Since a single logical operation may stretch across multiple calls to
248 * our entry point, errors have three parts:
249 *
250 * - errctx: an optional static string, describing the global operation
251 * currently in progress. Should be translated with
252 * libpq_gettext().
253 *
254 * - errbuf: contains the actual error message. Generally speaking, use
255 * actx_error[_str] to manipulate this. This must be filled
256 * with something useful on an error.
257 *
258 * - curl_err: an optional static error buffer used by libcurl to put
259 * detailed information about failures. Unfortunately
260 * untranslatable.
261 *
262 * These pieces will be combined into a single error message looking
263 * something like the following, with errctx and/or curl_err omitted when
264 * absent:
265 *
266 * connection to server ... failed: errctx: errbuf (libcurl: curl_err)
267 */
268 const char *errctx; /* not freed; must point to static allocation */
269 PQExpBufferData errbuf;
270 char curl_err[CURL_ERROR_SIZE];
271
272 /*
273 * These documents need to survive over multiple calls, and are therefore
274 * cached directly in the async_ctx.
275 */
276 struct provider provider;
277 struct device_authz authz;
278
279 int running; /* is asynchronous work in progress? */
280 bool user_prompted; /* have we already sent the authz prompt? */
281 bool used_basic_auth; /* did we send a client secret? */
282 bool debugging; /* can we give unsafe developer assistance? */
283 int dbg_num_calls; /* (debug mode) how many times were we called? */
284 };
285
286 /*
287 * Tears down the Curl handles and frees the async_ctx.
288 */
289 static void
290 free_async_ctx(PGconn *conn, struct async_ctx *actx)
291 {
292 /*
293 * In general, none of the error cases below should ever happen if we have
294 * no bugs above. But if we do hit them, surfacing those errors somehow
295 * might be the only way to have a chance to debug them.
296 *
297 * TODO: At some point it'd be nice to have a standard way to warn about
298 * teardown failures. Appending to the connection's error message only
299 * helps if the bug caused a connection failure; otherwise it'll be
300 * buried...
301 */
302
303 if (actx->curlm && actx->curl)
304 {
305 CURLMcode err = curl_multi_remove_handle(actx->curlm, actx->curl);
306
307 if (err)
308 libpq_append_conn_error(conn,
309 "libcurl easy handle removal failed: %s",
310 curl_multi_strerror(err));
311 }
312
313 if (actx->curl)
314 {
315 /*
316 * curl_multi_cleanup() doesn't free any associated easy handles; we
317 * need to do that separately. We only ever have one easy handle per
318 * multi handle.
319 */
320 curl_easy_cleanup(actx->curl);
321 }
322
323 if (actx->curlm)
324 {
325 CURLMcode err = curl_multi_cleanup(actx->curlm);
326
327 if (err)
328 libpq_append_conn_error(conn,
329 "libcurl multi handle cleanup failed: %s",
330 curl_multi_strerror(err));
331 }
332
333 free_provider(&actx->provider);
334 free_device_authz(&actx->authz);
335
336 curl_slist_free_all(actx->headers);
337 termPQExpBuffer(&actx->work_data);
338 termPQExpBuffer(&actx->errbuf);
339
340 if (actx->mux != PGINVALID_SOCKET)
341 close(actx->mux);
342 if (actx->timerfd >= 0)
343 close(actx->timerfd);
344
345 free(actx);
346 }
347
348 /*
349 * Release resources used for the asynchronous exchange and disconnect the
350 * altsock.
351 *
352 * This is called either at the end of a successful authentication, or during
353 * pqDropConnection(), so we won't leak resources even if PQconnectPoll() never
354 * calls us back.
355 */
356 void
357 pg_fe_cleanup_oauth_flow(PGconn *conn)
358 {
359 fe_oauth_state *state = conn_sasl_state(conn);
360
361 if (state->async_ctx)
362 {
363 free_async_ctx(conn, state->async_ctx);
364 state->async_ctx = NULL;
365 }
366
367 set_conn_altsock(conn, PGINVALID_SOCKET);
368 }
369
370 /*
371 * Macros for manipulating actx->errbuf. actx_error() translates and formats a
372 * string for you, actx_error_internal() is the untranslated equivalent, and
373 * actx_error_str() appends a string directly (also without translation).
374 */
375
376 #define actx_error(ACTX, FMT, ...) \
377 appendPQExpBuffer(&(ACTX)->errbuf, libpq_gettext(FMT), ##__VA_ARGS__)
378
379 #define actx_error_internal(ACTX, FMT, ...) \
380 appendPQExpBuffer(&(ACTX)->errbuf, FMT, ##__VA_ARGS__)
381
382 #define actx_error_str(ACTX, S) \
383 appendPQExpBufferStr(&(ACTX)->errbuf, S)
384
385 /*
386 * Macros for getting and setting state for the connection's two libcurl
387 * handles, so you don't have to write out the error handling every time.
388 */
389
390 #define CHECK_MSETOPT(ACTX, OPT, VAL, FAILACTION) \
391 do { \
392 struct async_ctx *_actx = (ACTX); \
393 CURLMcode _setopterr = curl_multi_setopt(_actx->curlm, OPT, VAL); \
394 if (_setopterr) { \
395 actx_error(_actx, "failed to set %s on OAuth connection: %s",\
396 #OPT, curl_multi_strerror(_setopterr)); \
397 FAILACTION; \
398 } \
399 } while (0)
400
401 #define CHECK_SETOPT(ACTX, OPT, VAL, FAILACTION) \
402 do { \
403 struct async_ctx *_actx = (ACTX); \
404 CURLcode _setopterr = curl_easy_setopt(_actx->curl, OPT, VAL); \
405 if (_setopterr) { \
406 actx_error(_actx, "failed to set %s on OAuth connection: %s",\
407 #OPT, curl_easy_strerror(_setopterr)); \
408 FAILACTION; \
409 } \
410 } while (0)
411
412 #define CHECK_GETINFO(ACTX, INFO, OUT, FAILACTION) \
413 do { \
414 struct async_ctx *_actx = (ACTX); \
415 CURLcode _getinfoerr = curl_easy_getinfo(_actx->curl, INFO, OUT); \
416 if (_getinfoerr) { \
417 actx_error(_actx, "failed to get %s from OAuth response: %s",\
418 #INFO, curl_easy_strerror(_getinfoerr)); \
419 FAILACTION; \
420 } \
421 } while (0)
422
423 /*
424 * General JSON Parsing for OAuth Responses
425 */
426
427 /*
428 * Represents a single name/value pair in a JSON object. This is the primary
429 * interface to parse_oauth_json().
430 *
431 * All fields are stored internally as strings or lists of strings, so clients
432 * have to explicitly parse other scalar types (though they will have gone
433 * through basic lexical validation). Storing nested objects is not currently
434 * supported, nor is parsing arrays of anything other than strings.
435 */
436 struct json_field
437 {
438 const char *name; /* name (key) of the member */
439
440 JsonTokenType type; /* currently supports JSON_TOKEN_STRING,
441 * JSON_TOKEN_NUMBER, and
442 * JSON_TOKEN_ARRAY_START */
443 union
444 {
445 char **scalar; /* for all scalar types */
446 struct curl_slist **array; /* for type == JSON_TOKEN_ARRAY_START */
447 } target;
448
449 bool required; /* REQUIRED field, or just OPTIONAL? */
450 };
451
452 /* Documentation macros for json_field.required. */
453 #define PG_OAUTH_REQUIRED true
454 #define PG_OAUTH_OPTIONAL false
455
456 /* Parse state for parse_oauth_json(). */
457 struct oauth_parse
458 {
459 PQExpBuffer errbuf; /* detail message for JSON_SEM_ACTION_FAILED */
460 int nested; /* nesting level (zero is the top) */
461
462 const struct json_field *fields; /* field definition array */
463 const struct json_field *active; /* points inside the fields array */
464 };
465
466 #define oauth_parse_set_error(ctx, fmt, ...) \
467 appendPQExpBuffer((ctx)->errbuf, libpq_gettext(fmt), ##__VA_ARGS__)
468
469 #define oauth_parse_set_error_internal(ctx, fmt, ...) \
470 appendPQExpBuffer((ctx)->errbuf, fmt, ##__VA_ARGS__)
471
472 static void
473 report_type_mismatch(struct oauth_parse *ctx)
474 {
475 char *msgfmt;
476
477 Assert(ctx->active);
478
479 /*
480 * At the moment, the only fields we're interested in are strings,
481 * numbers, and arrays of strings.
482 */
483 switch (ctx->active->type)
484 {
485 case JSON_TOKEN_STRING:
486 msgfmt = gettext_noop("field \"%s\" must be a string");
487 break;
488
489 case JSON_TOKEN_NUMBER:
490 msgfmt = gettext_noop("field \"%s\" must be a number");
491 break;
492
493 case JSON_TOKEN_ARRAY_START:
494 msgfmt = gettext_noop("field \"%s\" must be an array of strings");
495 break;
496
497 default:
498 Assert(false);
499 msgfmt = gettext_noop("field \"%s\" has unexpected type");
500 }
501
502 oauth_parse_set_error(ctx, msgfmt, ctx->active->name);
503 }
504
505 static JsonParseErrorType
506 oauth_json_object_start(void *state)
507 {
508 struct oauth_parse *ctx = state;
509
510 if (ctx->active)
511 {
512 /*
513 * Currently, none of the fields we're interested in can be or contain
514 * objects, so we can reject this case outright.
515 */
516 report_type_mismatch(ctx);
517 return JSON_SEM_ACTION_FAILED;
518 }
519
520 ++ctx->nested;
521 if (ctx->nested > MAX_OAUTH_NESTING_LEVEL)
522 {
523 oauth_parse_set_error(ctx, "JSON is too deeply nested");
524 return JSON_SEM_ACTION_FAILED;
525 }
526
527 return JSON_SUCCESS;
528 }
529
530 static JsonParseErrorType
531 oauth_json_object_field_start(void *state, char *name, bool isnull)
532 {
533 struct oauth_parse *ctx = state;
534
535 /* We care only about the top-level fields. */
536 if (ctx->nested == 1)
537 {
538 const struct json_field *field = ctx->fields;
539
540 /*
541 * We should never start parsing a new field while a previous one is
542 * still active.
543 */
544 if (ctx->active)
545 {
546 Assert(false);
547 oauth_parse_set_error_internal(ctx,
548 "internal error: started field \"%s\" before field \"%s\" was finished",
549 name, ctx->active->name);
550 return JSON_SEM_ACTION_FAILED;
551 }
552
553 while (field->name)
554 {
555 if (strcmp(name, field->name) == 0)
556 {
557 ctx->active = field;
558 break;
559 }
560
561 ++field;
562 }
563
564 /*
565 * We don't allow duplicate field names; error out if the target has
566 * already been set.
567 */
568 if (ctx->active)
569 {
570 field = ctx->active;
571
572 if ((field->type == JSON_TOKEN_ARRAY_START && *field->target.array)
573 || (field->type != JSON_TOKEN_ARRAY_START && *field->target.scalar))
574 {
575 oauth_parse_set_error(ctx, "field \"%s\" is duplicated",
576 field->name);
577 return JSON_SEM_ACTION_FAILED;
578 }
579 }
580 }
581
582 return JSON_SUCCESS;
583 }
584
585 static JsonParseErrorType
586 oauth_json_object_end(void *state)
587 {
588 struct oauth_parse *ctx = state;
589
590 --ctx->nested;
591
592 /*
593 * All fields should be fully processed by the end of the top-level
594 * object.
595 */
596 if (!ctx->nested && ctx->active)
597 {
598 Assert(false);
599 oauth_parse_set_error_internal(ctx,
600 "internal error: field \"%s\" still active at end of object",
601 ctx->active->name);
602 return JSON_SEM_ACTION_FAILED;
603 }
604
605 return JSON_SUCCESS;
606 }
607
608 static JsonParseErrorType
609 oauth_json_array_start(void *state)
610 {
611 struct oauth_parse *ctx = state;
612
613 if (!ctx->nested)
614 {
615 oauth_parse_set_error(ctx, "top-level element must be an object");
616 return JSON_SEM_ACTION_FAILED;
617 }
618
619 if (ctx->active)
620 {
621 if (ctx->active->type != JSON_TOKEN_ARRAY_START
622 /* The arrays we care about must not have arrays as values. */
623 || ctx->nested > 1)
624 {
625 report_type_mismatch(ctx);
626 return JSON_SEM_ACTION_FAILED;
627 }
628 }
629
630 ++ctx->nested;
631 if (ctx->nested > MAX_OAUTH_NESTING_LEVEL)
632 {
633 oauth_parse_set_error(ctx, "JSON is too deeply nested");
634 return JSON_SEM_ACTION_FAILED;
635 }
636
637 return JSON_SUCCESS;
638 }
639
640 static JsonParseErrorType
641 oauth_json_array_end(void *state)
642 {
643 struct oauth_parse *ctx = state;
644
645 if (ctx->active)
646 {
647 /*
648 * Clear the target (which should be an array inside the top-level
649 * object). For this to be safe, no target arrays can contain other
650 * arrays; we check for that in the array_start callback.
651 */
652 if (ctx->nested != 2 || ctx->active->type != JSON_TOKEN_ARRAY_START)
653 {
654 Assert(false);
655 oauth_parse_set_error_internal(ctx,
656 "internal error: found unexpected array end while parsing field \"%s\"",
657 ctx->active->name);
658 return JSON_SEM_ACTION_FAILED;
659 }
660
661 ctx->active = NULL;
662 }
663
664 --ctx->nested;
665 return JSON_SUCCESS;
666 }
667
668 static JsonParseErrorType
669 oauth_json_scalar(void *state, char *token, JsonTokenType type)
670 {
671 struct oauth_parse *ctx = state;
672
673 if (!ctx->nested)
674 {
675 oauth_parse_set_error(ctx, "top-level element must be an object");
676 return JSON_SEM_ACTION_FAILED;
677 }
678
679 if (ctx->active)
680 {
681 const struct json_field *field = ctx->active;
682 JsonTokenType expected = field->type;
683
684 /* Make sure this matches what the active field expects. */
685 if (expected == JSON_TOKEN_ARRAY_START)
686 {
687 /* Are we actually inside an array? */
688 if (ctx->nested < 2)
689 {
690 report_type_mismatch(ctx);
691 return JSON_SEM_ACTION_FAILED;
692 }
693
694 /* Currently, arrays can only contain strings. */
695 expected = JSON_TOKEN_STRING;
696 }
697
698 if (type != expected)
699 {
700 report_type_mismatch(ctx);
701 return JSON_SEM_ACTION_FAILED;
702 }
703
704 if (field->type != JSON_TOKEN_ARRAY_START)
705 {
706 /* Ensure that we're parsing the top-level keys... */
707 if (ctx->nested != 1)
708 {
709 Assert(false);
710 oauth_parse_set_error_internal(ctx,
711 "internal error: scalar target found at nesting level %d",
712 ctx->nested);
713 return JSON_SEM_ACTION_FAILED;
714 }
715
716 /* ...and that a result has not already been set. */
717 if (*field->target.scalar)
718 {
719 Assert(false);
720 oauth_parse_set_error_internal(ctx,
721 "internal error: scalar field \"%s\" would be assigned twice",
722 ctx->active->name);
723 return JSON_SEM_ACTION_FAILED;
724 }
725
726 *field->target.scalar = strdup(token);
727 if (!*field->target.scalar)
728 return JSON_OUT_OF_MEMORY;
729
730 ctx->active = NULL;
731
732 return JSON_SUCCESS;
733 }
734 else
735 {
736 struct curl_slist *temp;
737
738 /* The target array should be inside the top-level object. */
739 if (ctx->nested != 2)
740 {
741 Assert(false);
742 oauth_parse_set_error_internal(ctx,
743 "internal error: array member found at nesting level %d",
744 ctx->nested);
745 return JSON_SEM_ACTION_FAILED;
746 }
747
748 /* Note that curl_slist_append() makes a copy of the token. */
749 temp = curl_slist_append(*field->target.array, token);
750 if (!temp)
751 return JSON_OUT_OF_MEMORY;
752
753 *field->target.array = temp;
754 }
755 }
756 else
757 {
758 /* otherwise we just ignore it */
759 }
760
761 return JSON_SUCCESS;
762 }
763
764 /*
765 * Checks the Content-Type header against the expected type. Parameters are
766 * allowed but ignored.
767 */
768 static bool
769 check_content_type(struct async_ctx *actx, const char *type)
770 {
771 const size_t type_len = strlen(type);
772 char *content_type;
773
774 CHECK_GETINFO(actx, CURLINFO_CONTENT_TYPE, &content_type, return false);
775
776 if (!content_type)
777 {
778 actx_error(actx, "no content type was provided");
779 return false;
780 }
781
782 /*
783 * We need to perform a length limited comparison and not compare the
784 * whole string.
785 */
786 if (pg_strncasecmp(content_type, type, type_len) != 0)
787 goto fail;
788
789 /* On an exact match, we're done. */
790 Assert(strlen(content_type) >= type_len);
791 if (content_type[type_len] == '\0')
792 return true;
793
794 /*
795 * Only a semicolon (optionally preceded by HTTP optional whitespace) is
796 * acceptable after the prefix we checked. This marks the start of media
797 * type parameters, which we currently have no use for.
798 */
799 for (size_t i = type_len; content_type[i]; ++i)
800 {
801 switch (content_type[i])
802 {
803 case ';':
804 return true; /* success! */
805
806 case ' ':
807 case '\t':
808 /* HTTP optional whitespace allows only spaces and htabs. */
809 break;
810
811 default:
812 goto fail;
813 }
814 }
815
816 fail:
817 actx_error(actx, "unexpected content type: \"%s\"", content_type);
818 return false;
819 }
820
821 /*
822 * A helper function for general JSON parsing. fields is the array of field
823 * definitions with their backing pointers. The response will be parsed from
824 * actx->curl and actx->work_data (as set up by start_request()), and any
825 * parsing errors will be placed into actx->errbuf.
826 */
827 static bool
828 parse_oauth_json(struct async_ctx *actx, const struct json_field *fields)
829 {
830 PQExpBuffer resp = &actx->work_data;
831 JsonLexContext lex = {0};
832 JsonSemAction sem = {0};
833 JsonParseErrorType err;
834 struct oauth_parse ctx = {0};
835 bool success = false;
836
837 if (!check_content_type(actx, "application/json"))
838 return false;
839
840 if (strlen(resp->data) != resp->len)
841 {
842 actx_error(actx, "response contains embedded NULLs");
843 return false;
844 }
845
846 /*
847 * pg_parse_json doesn't validate the incoming UTF-8, so we have to check
848 * that up front.
849 */
850 if (pg_encoding_verifymbstr(PG_UTF8, resp->data, resp->len) != resp->len)
851 {
852 actx_error(actx, "response is not valid UTF-8");
853 return false;
854 }
855
856 makeJsonLexContextCstringLen(&lex, resp->data, resp->len, PG_UTF8, true);
857 setJsonLexContextOwnsTokens(&lex, true); /* must not leak on error */
858
859 ctx.errbuf = &actx->errbuf;
860 ctx.fields = fields;
861 sem.semstate = &ctx;
862
863 sem.object_start = oauth_json_object_start;
864 sem.object_field_start = oauth_json_object_field_start;
865 sem.object_end = oauth_json_object_end;
866 sem.array_start = oauth_json_array_start;
867 sem.array_end = oauth_json_array_end;
868 sem.scalar = oauth_json_scalar;
869
870 err = pg_parse_json(&lex, &sem);
871
872 if (err != JSON_SUCCESS)
873 {
874 /*
875 * For JSON_SEM_ACTION_FAILED, we've already written the error
876 * message. Other errors come directly from pg_parse_json(), already
877 * translated.
878 */
879 if (err != JSON_SEM_ACTION_FAILED)
880 actx_error_str(actx, json_errdetail(err, &lex));
881
882 goto cleanup;
883 }
884
885 /* Check all required fields. */
886 while (fields->name)
887 {
888 if (fields->required
889 && !*fields->target.scalar
890 && !*fields->target.array)
891 {
892 actx_error(actx, "field \"%s\" is missing", fields->name);
893 goto cleanup;
894 }
895
896 fields++;
897 }
898
899 success = true;
900
901 cleanup:
902 freeJsonLexContext(&lex);
903 return success;
904 }
905
906 /*
907 * JSON Parser Definitions
908 */
909
910 /*
911 * Parses authorization server metadata. Fields are defined by OIDC Discovery
912 * 1.0 and RFC 8414.
913 */
914 static bool
915 parse_provider(struct async_ctx *actx, struct provider *provider)
916 {
917 struct json_field fields[] = {
918 {"issuer", JSON_TOKEN_STRING, {&provider->issuer}, PG_OAUTH_REQUIRED},
919 {"token_endpoint", JSON_TOKEN_STRING, {&provider->token_endpoint}, PG_OAUTH_REQUIRED},
920
921 /*----
922 * The following fields are technically REQUIRED, but we don't use
923 * them anywhere yet:
924 *
925 * - jwks_uri
926 * - response_types_supported
927 * - subject_types_supported
928 * - id_token_signing_alg_values_supported
929 */
930
931 {"device_authorization_endpoint", JSON_TOKEN_STRING, {&provider->device_authorization_endpoint}, PG_OAUTH_OPTIONAL},
932 {"grant_types_supported", JSON_TOKEN_ARRAY_START, {.array = &provider->grant_types_supported}, PG_OAUTH_OPTIONAL},
933
934 {0},
935 };
936
937 return parse_oauth_json(actx, fields);
938 }
939
940 /*
941 * Parses a valid JSON number into a double. The input must have come from
942 * pg_parse_json(), so that we know the lexer has validated it; there's no
943 * in-band signal for invalid formats.
944 */
945 static double
946 parse_json_number(const char *s)
947 {
948 double parsed;
949 int cnt;
950
951 /*
952 * The JSON lexer has already validated the number, which is stricter than
953 * the %f format, so we should be good to use sscanf().
954 */
955 cnt = sscanf(s, "%lf", &parsed);
956
957 if (cnt != 1)
958 {
959 /*
960 * Either the lexer screwed up or our assumption above isn't true, and
961 * either way a developer needs to take a look.
962 */
963 Assert(false);
964 return 0;
965 }
966
967 return parsed;
968 }
969
970 /*
971 * Parses the "interval" JSON number, corresponding to the number of seconds to
972 * wait between token endpoint requests.
973 *
974 * RFC 8628 is pretty silent on sanity checks for the interval. As a matter of
975 * practicality, round any fractional intervals up to the next second, and clamp
976 * the result at a minimum of one. (Zero-second intervals would result in an
977 * expensive network polling loop.) Tests may remove the lower bound with
978 * PGOAUTHDEBUG, for improved performance.
979 */
980 static int32
981 parse_interval(struct async_ctx *actx, const char *interval_str)
982 {
983 double parsed;
984
985 parsed = parse_json_number(interval_str);
986 parsed = ceil(parsed);
987
988 if (parsed < 1)
989 return actx->debugging ? 0 : 1;
990
991 else if (parsed >= INT32_MAX)
992 return INT32_MAX;
993
994 return parsed;
995 }
996
997 /*
998 * Parses the "expires_in" JSON number, corresponding to the number of seconds
999 * remaining in the lifetime of the device code request.
1000 *
1001 * Similar to parse_interval, but we have even fewer requirements for reasonable
1002 * values since we don't use the expiration time directly (it's passed to the
1003 * PQAUTHDATA_PROMPT_OAUTH_DEVICE hook, in case the application wants to do
1004 * something with it). We simply round down and clamp to int range.
1005 */
1006 static int
1007 parse_expires_in(struct async_ctx *actx, const char *expires_in_str)
1008 {
1009 double parsed;
1010
1011 parsed = parse_json_number(expires_in_str);
1012 parsed = floor(parsed);
1013
1014 if (parsed >= INT_MAX)
1015 return INT_MAX;
1016 else if (parsed <= INT_MIN)
1017 return INT_MIN;
1018
1019 return parsed;
1020 }
1021
1022 /*
1023 * Parses the Device Authorization Response (RFC 8628, Sec. 3.2).
1024 */
1025 static bool
1026 parse_device_authz(struct async_ctx *actx, struct device_authz *authz)
1027 {
1028 struct json_field fields[] = {
1029 {"device_code", JSON_TOKEN_STRING, {&authz->device_code}, PG_OAUTH_REQUIRED},
1030 {"user_code", JSON_TOKEN_STRING, {&authz->user_code}, PG_OAUTH_REQUIRED},
1031 {"verification_uri", JSON_TOKEN_STRING, {&authz->verification_uri}, PG_OAUTH_REQUIRED},
1032 {"expires_in", JSON_TOKEN_NUMBER, {&authz->expires_in_str}, PG_OAUTH_REQUIRED},
1033
1034 /*
1035 * Some services (Google, Azure) spell verification_uri differently.
1036 * We accept either.
1037 */
1038 {"verification_url", JSON_TOKEN_STRING, {&authz->verification_uri}, PG_OAUTH_REQUIRED},
1039
1040 /*
1041 * There is no evidence of verification_uri_complete being spelled
1042 * with "url" instead with any service provider, so only support
1043 * "uri".
1044 */
1045 {"verification_uri_complete", JSON_TOKEN_STRING, {&authz->verification_uri_complete}, PG_OAUTH_OPTIONAL},
1046 {"interval", JSON_TOKEN_NUMBER, {&authz->interval_str}, PG_OAUTH_OPTIONAL},
1047
1048 {0},
1049 };
1050
1051 if (!parse_oauth_json(actx, fields))
1052 return false;
1053
1054 /*
1055 * Parse our numeric fields. Lexing has already completed by this time, so
1056 * we at least know they're valid JSON numbers.
1057 */
1058 if (authz->interval_str)
1059 authz->interval = parse_interval(actx, authz->interval_str);
1060 else
1061 {
1062 /*
1063 * RFC 8628 specifies 5 seconds as the default value if the server
1064 * doesn't provide an interval.
1065 */
1066 authz->interval = 5;
1067 }
1068
1069 Assert(authz->expires_in_str); /* ensured by parse_oauth_json() */
1070 authz->expires_in = parse_expires_in(actx, authz->expires_in_str);
1071
1072 return true;
1073 }
1074
1075 /*
1076 * Parses the device access token error response (RFC 8628, Sec. 3.5, which
1077 * uses the error response defined in RFC 6749, Sec. 5.2).
1078 */
1079 static bool
1080 parse_token_error(struct async_ctx *actx, struct token_error *err)
1081 {
1082 bool result;
1083 struct json_field fields[] = {
1084 {"error", JSON_TOKEN_STRING, {&err->error}, PG_OAUTH_REQUIRED},
1085
1086 {"error_description", JSON_TOKEN_STRING, {&err->error_description}, PG_OAUTH_OPTIONAL},
1087
1088 {0},
1089 };
1090
1091 result = parse_oauth_json(actx, fields);
1092
1093 /*
1094 * Since token errors are parsed during other active error paths, only
1095 * override the errctx if parsing explicitly fails.
1096 */
1097 if (!result)
1098 actx->errctx = libpq_gettext("failed to parse token error response");
1099
1100 return result;
1101 }
1102
1103 /*
1104 * Constructs a message from the token error response and puts it into
1105 * actx->errbuf.
1106 */
1107 static void
1108 record_token_error(struct async_ctx *actx, const struct token_error *err)
1109 {
1110 if (err->error_description)
1111 appendPQExpBuffer(&actx->errbuf, "%s ", err->error_description);
1112 else
1113 {
1114 /*
1115 * Try to get some more helpful detail into the error string. A 401
1116 * status in particular implies that the oauth_client_secret is
1117 * missing or wrong.
1118 */
1119 long response_code;
1120
1121 CHECK_GETINFO(actx, CURLINFO_RESPONSE_CODE, &response_code, response_code = 0);
1122
1123 if (response_code == 401)
1124 {
1125 actx_error(actx, actx->used_basic_auth
1126 ? gettext_noop("provider rejected the oauth_client_secret")
1127 : gettext_noop("provider requires client authentication, and no oauth_client_secret is set"));
1128 actx_error_str(actx, " ");
1129 }
1130 }
1131
1132 appendPQExpBuffer(&actx->errbuf, "(%s)", err->error);
1133 }
1134
1135 /*
1136 * Parses the device access token response (RFC 8628, Sec. 3.5, which uses the
1137 * success response defined in RFC 6749, Sec. 5.1).
1138 */
1139 static bool
1140 parse_access_token(struct async_ctx *actx, struct token *tok)
1141 {
1142 struct json_field fields[] = {
1143 {"access_token", JSON_TOKEN_STRING, {&tok->access_token}, PG_OAUTH_REQUIRED},
1144 {"token_type", JSON_TOKEN_STRING, {&tok->token_type}, PG_OAUTH_REQUIRED},
1145
1146 /*---
1147 * We currently have no use for the following OPTIONAL fields:
1148 *
1149 * - expires_in: This will be important for maintaining a token cache,
1150 * but we do not yet implement one.
1151 *
1152 * - refresh_token: Ditto.
1153 *
1154 * - scope: This is only sent when the authorization server sees fit to
1155 * change our scope request. It's not clear what we should do
1156 * about this; either it's been done as a matter of policy, or
1157 * the user has explicitly denied part of the authorization,
1158 * and either way the server-side validator is in a better
1159 * place to complain if the change isn't acceptable.
1160 */
1161
1162 {0},
1163 };
1164
1165 return parse_oauth_json(actx, fields);
1166 }
1167
1168 /*
1169 * libcurl Multi Setup/Callbacks
1170 */
1171
1172 /*
1173 * Sets up the actx->mux, which is the altsock that PQconnectPoll clients will
1174 * select() on instead of the Postgres socket during OAuth negotiation.
1175 *
1176 * This is just an epoll set or kqueue abstracting multiple other descriptors.
1177 * For epoll, the timerfd is always part of the set; it's just disabled when
1178 * we're not using it. For kqueue, the "timerfd" is actually a second kqueue
1179 * instance which is only added to the set when needed.
1180 */
1181 static bool
1182 setup_multiplexer(struct async_ctx *actx)
1183 {
1184 #if defined(HAVE_SYS_EPOLL_H)
1185 struct epoll_event ev = {.events = EPOLLIN};
1186
1187 actx->mux = epoll_create1(EPOLL_CLOEXEC);
1188 if (actx->mux < 0)
1189 {
1190 actx_error_internal(actx, "failed to create epoll set: %m");
1191 return false;
1192 }
1193
1194 actx->timerfd = timerfd_create(CLOCK_MONOTONIC, TFD_CLOEXEC);
1195 if (actx->timerfd < 0)
1196 {
1197 actx_error_internal(actx, "failed to create timerfd: %m");
1198 return false;
1199 }
1200
1201 if (epoll_ctl(actx->mux, EPOLL_CTL_ADD, actx->timerfd, &ev) < 0)
1202 {
1203 actx_error_internal(actx, "failed to add timerfd to epoll set: %m");
1204 return false;
1205 }
1206
1207 return true;
1208 #elif defined(HAVE_SYS_EVENT_H)
1209 actx->mux = kqueue();
1210 if (actx->mux < 0)
1211 {
1212 actx_error_internal(actx, "failed to create kqueue: %m");
1213 return false;
1214 }
1215
1216 /*
1217 * Originally, we set EVFILT_TIMER directly on the top-level multiplexer.
1218 * This makes it difficult to implement timer_expired(), though, so now we
1219 * set EVFILT_TIMER on a separate actx->timerfd, which is chained to
1220 * actx->mux while the timer is active.
1221 */
1222 actx->timerfd = kqueue();
1223 if (actx->timerfd < 0)
1224 {
1225 actx_error_internal(actx, "failed to create timer kqueue: %m");
1226 return false;
1227 }
1228
1229 return true;
1230 #else
1231 #error setup_multiplexer is not implemented on this platform
1232 #endif
1233 }
1234
1235 /*
1236 * Adds and removes sockets from the multiplexer set, as directed by the
1237 * libcurl multi handle.
1238 */
1239 static int
1240 register_socket(CURL *curl, curl_socket_t socket, int what, void *ctx,
1241 void *socketp)
1242 {
1243 struct async_ctx *actx = ctx;
1244
1245 #if defined(HAVE_SYS_EPOLL_H)
1246 struct epoll_event ev = {0};
1247 int res;
1248 int op = EPOLL_CTL_ADD;
1249
1250 switch (what)
1251 {
1252 case CURL_POLL_IN:
1253 ev.events = EPOLLIN;
1254 break;
1255
1256 case CURL_POLL_OUT:
1257 ev.events = EPOLLOUT;
1258 break;
1259
1260 case CURL_POLL_INOUT:
1261 ev.events = EPOLLIN | EPOLLOUT;
1262 break;
1263
1264 case CURL_POLL_REMOVE:
1265 op = EPOLL_CTL_DEL;
1266 break;
1267
1268 default:
1269 actx_error_internal(actx, "unknown libcurl socket operation: %d", what);
1270 return -1;
1271 }
1272
1273 res = epoll_ctl(actx->mux, op, socket, &ev);
1274 if (res < 0 && errno == EEXIST)
1275 {
1276 /* We already had this socket in the poll set. */
1277 op = EPOLL_CTL_MOD;
1278 res = epoll_ctl(actx->mux, op, socket, &ev);
1279 }
1280
1281 if (res < 0)
1282 {
1283 switch (op)
1284 {
1285 case EPOLL_CTL_ADD:
1286 actx_error_internal(actx, "could not add to epoll set: %m");
1287 break;
1288
1289 case EPOLL_CTL_DEL:
1290 actx_error_internal(actx, "could not delete from epoll set: %m");
1291 break;
1292
1293 default:
1294 actx_error_internal(actx, "could not update epoll set: %m");
1295 }
1296
1297 return -1;
1298 }
1299
1300 return 0;
1301 #elif defined(HAVE_SYS_EVENT_H)
1302 struct kevent ev[2];
1303 struct kevent ev_out[2];
1304 struct timespec timeout = {0};
1305 int nev = 0;
1306 int res;
1307
1308 /*
1309 * We don't know which of the events is currently registered, perhaps
1310 * both, so we always try to remove unneeded events. This means we need to
1311 * tolerate ENOENT below.
1312 */
1313 switch (what)
1314 {
1315 case CURL_POLL_IN:
1316 EV_SET(&ev[nev], socket, EVFILT_READ, EV_ADD | EV_RECEIPT, 0, 0, 0);
1317 nev++;
1318 EV_SET(&ev[nev], socket, EVFILT_WRITE, EV_DELETE | EV_RECEIPT, 0, 0, 0);
1319 nev++;
1320 break;
1321
1322 case CURL_POLL_OUT:
1323 EV_SET(&ev[nev], socket, EVFILT_WRITE, EV_ADD | EV_RECEIPT, 0, 0, 0);
1324 nev++;
1325 EV_SET(&ev[nev], socket, EVFILT_READ, EV_DELETE | EV_RECEIPT, 0, 0, 0);
1326 nev++;
1327 break;
1328
1329 case CURL_POLL_INOUT:
1330 EV_SET(&ev[nev], socket, EVFILT_READ, EV_ADD | EV_RECEIPT, 0, 0, 0);
1331 nev++;
1332 EV_SET(&ev[nev], socket, EVFILT_WRITE, EV_ADD | EV_RECEIPT, 0, 0, 0);
1333 nev++;
1334 break;
1335
1336 case CURL_POLL_REMOVE:
1337 EV_SET(&ev[nev], socket, EVFILT_READ, EV_DELETE | EV_RECEIPT, 0, 0, 0);
1338 nev++;
1339 EV_SET(&ev[nev], socket, EVFILT_WRITE, EV_DELETE | EV_RECEIPT, 0, 0, 0);
1340 nev++;
1341 break;
1342
1343 default:
1344 actx_error_internal(actx, "unknown libcurl socket operation: %d", what);
1345 return -1;
1346 }
1347
1348 Assert(nev <= lengthof(ev));
1349 Assert(nev <= lengthof(ev_out));
1350
1351 res = kevent(actx->mux, ev, nev, ev_out, nev, &timeout);
1352 if (res < 0)
1353 {
1354 actx_error_internal(actx, "could not modify kqueue: %m");
1355 return -1;
1356 }
1357
1358 /*
1359 * We can't use the simple errno version of kevent, because we need to
1360 * skip over ENOENT while still allowing a second change to be processed.
1361 * So we need a longer-form error checking loop.
1362 */
1363 for (int i = 0; i < res; ++i)
1364 {
1365 /*
1366 * EV_RECEIPT should guarantee one EV_ERROR result for every change,
1367 * whether successful or not. Failed entries contain a non-zero errno
1368 * in the data field.
1369 */
1370 Assert(ev_out[i].flags & EV_ERROR);
1371
1372 errno = ev_out[i].data;
1373 if (errno && errno != ENOENT)
1374 {
1375 switch (what)
1376 {
1377 case CURL_POLL_REMOVE:
1378 actx_error_internal(actx, "could not delete from kqueue: %m");
1379 break;
1380 default:
1381 actx_error_internal(actx, "could not add to kqueue: %m");
1382 }
1383 return -1;
1384 }
1385 }
1386
1387 return 0;
1388 #else
1389 #error register_socket is not implemented on this platform
1390 #endif
1391 }
1392
1393 /*
1394 * If there is no work to do on any of the descriptors in the multiplexer, then
1395 * this function must ensure that the multiplexer is not readable.
1396 *
1397 * Unlike epoll descriptors, kqueue descriptors only transition from readable to
1398 * unreadable when kevent() is called and finds nothing, after removing
1399 * level-triggered conditions that have gone away. We therefore need a dummy
1400 * kevent() call after operations might have been performed on the monitored
1401 * sockets or timer_fd. Any event returned is ignored here, but it also remains
1402 * queued (being level-triggered) and leaves the descriptor readable. This is a
1403 * no-op for epoll descriptors.
1404 */
1405 static bool
1406 comb_multiplexer(struct async_ctx *actx)
1407 {
1408 #if defined(HAVE_SYS_EPOLL_H)
1409 /* The epoll implementation doesn't hold onto stale events. */
1410 return true;
1411 #elif defined(HAVE_SYS_EVENT_H)
1412 struct timespec timeout = {0};
1413 struct kevent ev;
1414
1415 /*
1416 * Try to read a single pending event. We can actually ignore the result:
1417 * either we found an event to process, in which case the multiplexer is
1418 * correctly readable for that event at minimum, and it doesn't matter if
1419 * there are any stale events; or we didn't find any, in which case the
1420 * kernel will have discarded any stale events as it traveled to the end
1421 * of the queue.
1422 *
1423 * Note that this depends on our registrations being level-triggered --
1424 * even the timer, so we use a chained kqueue for that instead of an
1425 * EVFILT_TIMER on the top-level mux. If we used edge-triggered events,
1426 * this call would improperly discard them.
1427 */
1428 if (kevent(actx->mux, NULL, 0, &ev, 1, &timeout) < 0)
1429 {
1430 actx_error_internal(actx, "could not comb kqueue: %m");
1431 return false;
1432 }
1433
1434 return true;
1435 #else
1436 #error comb_multiplexer is not implemented on this platform
1437 #endif
1438 }
1439
1440 /*
1441 * Enables or disables the timer in the multiplexer set. The timeout value is
1442 * in milliseconds (negative values disable the timer).
1443 *
1444 * For epoll, rather than continually adding and removing the timer, we keep it
1445 * in the set at all times and just disarm it when it's not needed. For kqueue,
1446 * the timer is removed completely when disabled to prevent stale timeouts from
1447 * remaining in the queue.
1448 *
1449 * To meet Curl requirements for the CURLMOPT_TIMERFUNCTION, implementations of
1450 * set_timer must handle repeated calls by fully discarding any previous running
1451 * or expired timer.
1452 */
1453 static bool
1454 set_timer(struct async_ctx *actx, long timeout)
1455 {
1456 #if defined(HAVE_SYS_EPOLL_H)
1457 struct itimerspec spec = {0};
1458
1459 if (timeout < 0)
1460 {
1461 /* the zero itimerspec will disarm the timer below */
1462 }
1463 else if (timeout == 0)
1464 {
1465 /*
1466 * A zero timeout means libcurl wants us to call back immediately.
1467 * That's not technically an option for timerfd, but we can make the
1468 * timeout ridiculously short.
1469 */
1470 spec.it_value.tv_nsec = 1;
1471 }
1472 else
1473 {
1474 spec.it_value.tv_sec = timeout / 1000;
1475 spec.it_value.tv_nsec = (timeout % 1000) * 1000000;
1476 }
1477
1478 if (timerfd_settime(actx->timerfd, 0 /* no flags */ , &spec, NULL) < 0)
1479 {
1480 actx_error_internal(actx, "setting timerfd to %ld: %m", timeout);
1481 return false;
1482 }
1483
1484 return true;
1485 #elif defined(HAVE_SYS_EVENT_H)
1486 struct kevent ev;
1487
1488 #ifdef __NetBSD__
1489
1490 /*
1491 * Work around NetBSD's rejection of zero timeouts (EINVAL), a bit like
1492 * timerfd above.
1493 */
1494 if (timeout == 0)
1495 timeout = 1;
1496 #endif
1497
1498 /*
1499 * Always disable the timer, and remove it from the multiplexer, to clear
1500 * out any already-queued events. (On some BSDs, adding an EVFILT_TIMER to
1501 * a kqueue that already has one will clear stale events, but not on
1502 * macOS.)
1503 *
1504 * If there was no previous timer set, the kevent calls will result in
1505 * ENOENT, which is fine.
1506 */
1507 EV_SET(&ev, 1, EVFILT_TIMER, EV_DELETE, 0, 0, 0);
1508 if (kevent(actx->timerfd, &ev, 1, NULL, 0, NULL) < 0 && errno != ENOENT)
1509 {
1510 actx_error_internal(actx, "deleting kqueue timer: %m");
1511 return false;
1512 }
1513
1514 EV_SET(&ev, actx->timerfd, EVFILT_READ, EV_DELETE, 0, 0, 0);
1515 if (kevent(actx->mux, &ev, 1, NULL, 0, NULL) < 0 && errno != ENOENT)
1516 {
1517 actx_error_internal(actx, "removing kqueue timer from multiplexer: %m");
1518 return false;
1519 }
1520
1521 /* If we're not adding a timer, we're done. */
1522 if (timeout < 0)
1523 return true;
1524
1525 EV_SET(&ev, 1, EVFILT_TIMER, (EV_ADD | EV_ONESHOT), 0, timeout, 0);
1526 if (kevent(actx->timerfd, &ev, 1, NULL, 0, NULL) < 0)
1527 {
1528 actx_error_internal(actx, "setting kqueue timer to %ld: %m", timeout);
1529 return false;
1530 }
1531
1532 EV_SET(&ev, actx->timerfd, EVFILT_READ, EV_ADD, 0, 0, 0);
1533 if (kevent(actx->mux, &ev, 1, NULL, 0, NULL) < 0)
1534 {
1535 actx_error_internal(actx, "adding kqueue timer to multiplexer: %m");
1536 return false;
1537 }
1538
1539 return true;
1540 #else
1541 #error set_timer is not implemented on this platform
1542 #endif
1543 }
1544
1545 /*
1546 * Returns 1 if the timeout in the multiplexer set has expired since the last
1547 * call to set_timer(), 0 if the timer is either still running or disarmed, or
1548 * -1 (with an actx_error() report) if the timer cannot be queried.
1549 */
1550 static int
1551 timer_expired(struct async_ctx *actx)
1552 {
1553 #if defined(HAVE_SYS_EPOLL_H) || defined(HAVE_SYS_EVENT_H)
1554 int res;
1555
1556 /* Is the timer ready? */
1557 res = PQsocketPoll(actx->timerfd, 1 /* forRead */ , 0, 0);
1558 if (res < 0)
1559 {
1560 actx_error(actx, "checking timer expiration: %m");
1561 return -1;
1562 }
1563
1564 return (res > 0);
1565 #else
1566 #error timer_expired is not implemented on this platform
1567 #endif
1568 }
1569
1570 /*
1571 * Adds or removes timeouts from the multiplexer set, as directed by the
1572 * libcurl multi handle.
1573 */
1574 static int
1575 register_timer(CURLM *curlm, long timeout, void *ctx)
1576 {
1577 struct async_ctx *actx = ctx;
1578
1579 /*
1580 * There might be an optimization opportunity here: if timeout == 0, we
1581 * could signal drive_request to immediately call
1582 * curl_multi_socket_action, rather than returning all the way up the
1583 * stack only to come right back. But it's not clear that the additional
1584 * code complexity is worth it.
1585 */
1586 if (!set_timer(actx, timeout))
1587 return -1; /* actx_error already called */
1588
1589 return 0;
1590 }
1591
1592 /*
1593 * Removes any expired-timer event from the multiplexer. If was_expired is not
1594 * NULL, it will contain whether or not the timer was expired at time of call.
1595 */
1596 static bool
1597 drain_timer_events(struct async_ctx *actx, bool *was_expired)
1598 {
1599 int res;
1600
1601 res = timer_expired(actx);
1602 if (res < 0)
1603 return false;
1604
1605 if (res > 0)
1606 {
1607 /*
1608 * Timer is expired. We could drain the event manually from the
1609 * timerfd, but it's easier to simply disable it; that keeps the
1610 * platform-specific code in set_timer().
1611 */
1612 if (!set_timer(actx, -1))
1613 return false;
1614 }
1615
1616 if (was_expired)
1617 *was_expired = (res > 0);
1618
1619 return true;
1620 }
1621
1622 /*
1623 * Prints Curl request debugging information to stderr.
1624 *
1625 * Note that this will expose a number of critical secrets, so users have to opt
1626 * into this (see PGOAUTHDEBUG).
1627 */
1628 static int
1629 debug_callback(CURL *handle, curl_infotype type, char *data, size_t size,
1630 void *clientp)
1631 {
1632 const char *prefix;
1633 bool printed_prefix = false;
1634 PQExpBufferData buf;
1635
1636 /* Prefixes are modeled off of the default libcurl debug output. */
1637 switch (type)
1638 {
1639 case CURLINFO_TEXT:
1640 prefix = "*";
1641 break;
1642
1643 case CURLINFO_HEADER_IN: /* fall through */
1644 case CURLINFO_DATA_IN:
1645 prefix = "<";
1646 break;
1647
1648 case CURLINFO_HEADER_OUT: /* fall through */
1649 case CURLINFO_DATA_OUT:
1650 prefix = ">";
1651 break;
1652
1653 default:
1654 return 0;
1655 }
1656
1657 initPQExpBuffer(&buf);
1658
1659 /*
1660 * Split the output into lines for readability; sometimes multiple headers
1661 * are included in a single call. We also don't allow unprintable ASCII
1662 * through without a basic <XX> escape.
1663 */
1664 for (int i = 0; i < size; i++)
1665 {
1666 char c = data[i];
1667
1668 if (!printed_prefix)
1669 {
1670 appendPQExpBuffer(&buf, "[libcurl] %s ", prefix);
1671 printed_prefix = true;
1672 }
1673
1674 if (c >= 0x20 && c <= 0x7E)
1675 appendPQExpBufferChar(&buf, c);
1676 else if ((type == CURLINFO_HEADER_IN
1677 || type == CURLINFO_HEADER_OUT
1678 || type == CURLINFO_TEXT)
1679 && (c == '\r' || c == '\n'))
1680 {
1681 /*
1682 * Don't bother emitting <0D><0A> for headers and text; it's not
1683 * helpful noise.
1684 */
1685 }
1686 else
1687 appendPQExpBuffer(&buf, "<%02X>", c);
1688
1689 if (c == '\n')
1690 {
1691 appendPQExpBufferChar(&buf, c);
1692 printed_prefix = false;
1693 }
1694 }
1695
1696 if (printed_prefix)
1697 appendPQExpBufferChar(&buf, '\n'); /* finish the line */
1698
1699 fprintf(stderr, "%s", buf.data);
1700 termPQExpBuffer(&buf);
1701 return 0;
1702 }
1703
1704 /*
1705 * Initializes the two libcurl handles in the async_ctx. The multi handle,
1706 * actx->curlm, is what drives the asynchronous engine and tells us what to do
1707 * next. The easy handle, actx->curl, encapsulates the state for a single
1708 * request/response. It's added to the multi handle as needed, during
1709 * start_request().
1710 */
1711 static bool
1712 setup_curl_handles(struct async_ctx *actx)
1713 {
1714 /*
1715 * Create our multi handle. This encapsulates the entire conversation with
1716 * libcurl for this connection.
1717 */
1718 actx->curlm = curl_multi_init();
1719 if (!actx->curlm)
1720 {
1721 /* We don't get a lot of feedback on the failure reason. */
1722 actx_error(actx, "failed to create libcurl multi handle");
1723 return false;
1724 }
1725
1726 /*
1727 * The multi handle tells us what to wait on using two callbacks. These
1728 * will manipulate actx->mux as needed.
1729 */
1730 CHECK_MSETOPT(actx, CURLMOPT_SOCKETFUNCTION, register_socket, return false);
1731 CHECK_MSETOPT(actx, CURLMOPT_SOCKETDATA, actx, return false);
1732 CHECK_MSETOPT(actx, CURLMOPT_TIMERFUNCTION, register_timer, return false);
1733 CHECK_MSETOPT(actx, CURLMOPT_TIMERDATA, actx, return false);
1734
1735 /*
1736 * Set up an easy handle. All of our requests are made serially, so we
1737 * only ever need to keep track of one.
1738 */
1739 actx->curl = curl_easy_init();
1740 if (!actx->curl)
1741 {
1742 actx_error(actx, "failed to create libcurl handle");
1743 return false;
1744 }
1745
1746 /*
1747 * Multi-threaded applications must set CURLOPT_NOSIGNAL. This requires us
1748 * to handle the possibility of SIGPIPE ourselves using pq_block_sigpipe;
1749 * see pg_fe_run_oauth_flow().
1750 *
1751 * NB: If libcurl is not built against a friendly DNS resolver (c-ares or
1752 * threaded), setting this option prevents DNS lookups from timing out
1753 * correctly. We warn about this situation at configure time.
1754 *
1755 * TODO: Perhaps there's a clever way to warn the user about synchronous
1756 * DNS at runtime too? It's not immediately clear how to do that in a
1757 * helpful way: for many standard single-threaded use cases, the user
1758 * might not care at all, so spraying warnings to stderr would probably do
1759 * more harm than good.
1760 */
1761 CHECK_SETOPT(actx, CURLOPT_NOSIGNAL, 1L, return false);
1762
1763 if (actx->debugging)
1764 {
1765 /*
1766 * Set a callback for retrieving error information from libcurl, the
1767 * function only takes effect when CURLOPT_VERBOSE has been set so
1768 * make sure the order is kept.
1769 */
1770 CHECK_SETOPT(actx, CURLOPT_DEBUGFUNCTION, debug_callback, return false);
1771 CHECK_SETOPT(actx, CURLOPT_VERBOSE, 1L, return false);
1772 }
1773
1774 CHECK_SETOPT(actx, CURLOPT_ERRORBUFFER, actx->curl_err, return false);
1775
1776 /*
1777 * Only HTTPS is allowed. (Debug mode additionally allows HTTP; this is
1778 * intended for testing only.)
1779 *
1780 * There's a bit of unfortunate complexity around the choice of
1781 * CURLoption. CURLOPT_PROTOCOLS is deprecated in modern Curls, but its
1782 * replacement didn't show up until relatively recently.
1783 */
1784 {
1785 #if CURL_AT_LEAST_VERSION(7, 85, 0)
1786 const CURLoption popt = CURLOPT_PROTOCOLS_STR;
1787 const char *protos = "https";
1788 const char *const unsafe = "https,http";
1789 #else
1790 const CURLoption popt = CURLOPT_PROTOCOLS;
1791 long protos = CURLPROTO_HTTPS;
1792 const long unsafe = CURLPROTO_HTTPS | CURLPROTO_HTTP;
1793 #endif
1794
1795 if (actx->debugging)
1796 protos = unsafe;
1797
1798 CHECK_SETOPT(actx, popt, protos, return false);
1799 }
1800
1801 /*
1802 * If we're in debug mode, allow the developer to change the trusted CA
1803 * list. For now, this is not something we expose outside of the UNSAFE
1804 * mode, because it's not clear that it's useful in production: both libpq
1805 * and the user's browser must trust the same authorization servers for
1806 * the flow to work at all, so any changes to the roots are likely to be
1807 * done system-wide.
1808 */
1809 if (actx->debugging)
1810 {
1811 const char *env;
1812
1813 if ((env = getenv("PGOAUTHCAFILE")) != NULL)
1814 CHECK_SETOPT(actx, CURLOPT_CAINFO, env, return false);
1815 }
1816
1817 /*
1818 * Suppress the Accept header to make our request as minimal as possible.
1819 * (Ideally we would set it to "application/json" instead, but OpenID is
1820 * pretty strict when it comes to provider behavior, so we have to check
1821 * what comes back anyway.)
1822 */
1823 actx->headers = curl_slist_append(actx->headers, "Accept:");
1824 if (actx->headers == NULL)
1825 {
1826 actx_error(actx, "out of memory");
1827 return false;
1828 }
1829 CHECK_SETOPT(actx, CURLOPT_HTTPHEADER, actx->headers, return false);
1830
1831 return true;
1832 }
1833
1834 /*
1835 * Generic HTTP Request Handlers
1836 */
1837
1838 /*
1839 * Response callback from libcurl which appends the response body into
1840 * actx->work_data (see start_request()). The maximum size of the data is
1841 * defined by CURL_MAX_WRITE_SIZE which by default is 16kb (and can only be
1842 * changed by recompiling libcurl).
1843 */
1844 static size_t
1845 append_data(char *buf, size_t size, size_t nmemb, void *userdata)
1846 {
1847 struct async_ctx *actx = userdata;
1848 PQExpBuffer resp = &actx->work_data;
1849 size_t len = size * nmemb;
1850
1851 /* In case we receive data over the threshold, abort the transfer */
1852 if ((resp->len + len) > MAX_OAUTH_RESPONSE_SIZE)
1853 {
1854 actx_error(actx, "response is too large");
1855 return 0;
1856 }
1857
1858 /* The data passed from libcurl is not null-terminated */
1859 appendBinaryPQExpBuffer(resp, buf, len);
1860
1861 /*
1862 * Signal an error in order to abort the transfer in case we ran out of
1863 * memory in accepting the data.
1864 */
1865 if (PQExpBufferBroken(resp))
1866 {
1867 actx_error(actx, "out of memory");
1868 return 0;
1869 }
1870
1871 return len;
1872 }
1873
1874 /*
1875 * Begins an HTTP request on the multi handle. The caller should have set up all
1876 * request-specific options on actx->curl first. The server's response body will
1877 * be accumulated in actx->work_data (which will be reset, so don't store
1878 * anything important there across this call).
1879 *
1880 * Once a request is queued, it can be driven to completion via drive_request().
1881 * If actx->running is zero upon return, the request has already finished and
1882 * drive_request() can be called without returning control to the client.
1883 */
1884 static bool
1885 start_request(struct async_ctx *actx)
1886 {
1887 CURLMcode err;
1888
1889 resetPQExpBuffer(&actx->work_data);
1890 CHECK_SETOPT(actx, CURLOPT_WRITEFUNCTION, append_data, return false);
1891 CHECK_SETOPT(actx, CURLOPT_WRITEDATA, actx, return false);
1892
1893 err = curl_multi_add_handle(actx->curlm, actx->curl);
1894 if (err)
1895 {
1896 actx_error(actx, "failed to queue HTTP request: %s",
1897 curl_multi_strerror(err));
1898 return false;
1899 }
1900
1901 /*
1902 * actx->running tracks the number of running handles, so we can
1903 * immediately call back if no waiting is needed.
1904 *
1905 * Even though this is nominally an asynchronous process, there are some
1906 * operations that can synchronously fail by this point (e.g. connections
1907 * to closed local ports) or even synchronously succeed if the stars align
1908 * (all the libcurl connection caches hit and the server is fast).
1909 */
1910 err = curl_multi_socket_action(actx->curlm, CURL_SOCKET_TIMEOUT, 0, &actx->running);
1911 if (err)
1912 {
1913 actx_error(actx, "asynchronous HTTP request failed: %s",
1914 curl_multi_strerror(err));
1915 return false;
1916 }
1917
1918 return true;
1919 }
1920
1921 /*
1922 * CURL_IGNORE_DEPRECATION was added in 7.87.0. If it's not defined, we can make
1923 * it a no-op.
1924 */
1925 #ifndef CURL_IGNORE_DEPRECATION
1926 #define CURL_IGNORE_DEPRECATION(x) x
1927 #endif
1928
1929 /*
1930 * Add another macro layer that inserts the needed semicolon, to avoid having
1931 * to write a literal semicolon in the call below, which would break pgindent.
1932 */
1933 #define PG_CURL_IGNORE_DEPRECATION(x) CURL_IGNORE_DEPRECATION(x;)
1934
1935 /*
1936 * Drives the multi handle towards completion. The caller should have already
1937 * set up an asynchronous request via start_request().
1938 */
1939 static PostgresPollingStatusType
1940 drive_request(struct async_ctx *actx)
1941 {
1942 CURLMcode err;
1943 CURLMsg *msg;
1944 int msgs_left;
1945 bool done;
1946
1947 if (actx->running)
1948 {
1949 /*---
1950 * There's an async request in progress. Pump the multi handle.
1951 *
1952 * curl_multi_socket_all() is officially deprecated, because it's
1953 * inefficient and pointless if your event loop has already handed you
1954 * the exact sockets that are ready. But that's not our use case --
1955 * our client has no way to tell us which sockets are ready. (They
1956 * don't even know there are sockets to begin with.)
1957 *
1958 * We can grab the list of triggered events from the multiplexer
1959 * ourselves, but that's effectively what curl_multi_socket_all() is
1960 * going to do. And there are currently no plans for the Curl project
1961 * to remove or break this API, so ignore the deprecation. See
1962 *
1963 * https://curl.se/mail/lib-2024-11/0028.html
1964 */
1965 PG_CURL_IGNORE_DEPRECATION(err =
1966 curl_multi_socket_all(actx->curlm,
1967 &actx->running));
1968
1969 if (err)
1970 {
1971 actx_error(actx, "asynchronous HTTP request failed: %s",
1972 curl_multi_strerror(err));
1973 return PGRES_POLLING_FAILED;
1974 }
1975
1976 if (actx->running)
1977 {
1978 /* We'll come back again. */
1979 return PGRES_POLLING_READING;
1980 }
1981 }
1982
1983 done = false;
1984 while ((msg = curl_multi_info_read(actx->curlm, &msgs_left)) != NULL)
1985 {
1986 if (msg->msg != CURLMSG_DONE)
1987 {
1988 /*
1989 * Future libcurl versions may define new message types; we don't
1990 * know how to handle them, so we'll ignore them.
1991 */
1992 continue;
1993 }
1994
1995 /* First check the status of the request itself. */
1996 if (msg->data.result != CURLE_OK)
1997 {
1998 /*
1999 * If a more specific error hasn't already been reported, use
2000 * libcurl's description.
2001 */
2002 if (actx->errbuf.len == 0)
2003 actx_error_str(actx, curl_easy_strerror(msg->data.result));
2004
2005 return PGRES_POLLING_FAILED;
2006 }
2007
2008 /* Now remove the finished handle; we'll add it back later if needed. */
2009 err = curl_multi_remove_handle(actx->curlm, msg->easy_handle);
2010 if (err)
2011 {
2012 actx_error(actx, "libcurl easy handle removal failed: %s",
2013 curl_multi_strerror(err));
2014 return PGRES_POLLING_FAILED;
2015 }
2016
2017 done = true;
2018 }
2019
2020 /* Sanity check. */
2021 if (!done)
2022 {
2023 actx_error(actx, "no result was retrieved for the finished handle");
2024 return PGRES_POLLING_FAILED;
2025 }
2026
2027 return PGRES_POLLING_OK;
2028 }
2029
2030 /*
2031 * URL-Encoding Helpers
2032 */
2033
2034 /*
2035 * Encodes a string using the application/x-www-form-urlencoded format, and
2036 * appends it to the given buffer.
2037 */
2038 static void
2039 append_urlencoded(PQExpBuffer buf, const char *s)
2040 {
2041 char *escaped;
2042 char *haystack;
2043 char *match;
2044
2045 /* The first parameter to curl_easy_escape is deprecated by Curl */
2046 escaped = curl_easy_escape(NULL, s, 0);
2047 if (!escaped)
2048 {
2049 termPQExpBuffer(buf); /* mark the buffer broken */
2050 return;
2051 }
2052
2053 /*
2054 * curl_easy_escape() almost does what we want, but we need the
2055 * query-specific flavor which uses '+' instead of '%20' for spaces. The
2056 * Curl command-line tool does this with a simple search-and-replace, so
2057 * follow its lead.
2058 */
2059 haystack = escaped;
2060
2061 while ((match = strstr(haystack, "%20")) != NULL)
2062 {
2063 /* Append the unmatched portion, followed by the plus sign. */
2064 appendBinaryPQExpBuffer(buf, haystack, match - haystack);
2065 appendPQExpBufferChar(buf, '+');
2066
2067 /* Keep searching after the match. */
2068 haystack = match + 3 /* strlen("%20") */ ;
2069 }
2070
2071 /* Push the remainder of the string onto the buffer. */
2072 appendPQExpBufferStr(buf, haystack);
2073
2074 curl_free(escaped);
2075 }
2076
2077 /*
2078 * Convenience wrapper for encoding a single string. Returns NULL on allocation
2079 * failure.
2080 */
2081 static char *
2082 urlencode(const char *s)
2083 {
2084 PQExpBufferData buf;
2085
2086 initPQExpBuffer(&buf);
2087 append_urlencoded(&buf, s);
2088
2089 return PQExpBufferDataBroken(buf) ? NULL : buf.data;
2090 }
2091
2092 /*
2093 * Appends a key/value pair to the end of an application/x-www-form-urlencoded
2094 * list.
2095 */
2096 static void
2097 build_urlencoded(PQExpBuffer buf, const char *key, const char *value)
2098 {
2099 if (buf->len)
2100 appendPQExpBufferChar(buf, '&');
2101
2102 append_urlencoded(buf, key);
2103 appendPQExpBufferChar(buf, '=');
2104 append_urlencoded(buf, value);
2105 }
2106
2107 /*
2108 * Specific HTTP Request Handlers
2109 *
2110 * This is finally the beginning of the actual application logic. Generally
2111 * speaking, a single request consists of a start_* and a finish_* step, with
2112 * drive_request() pumping the machine in between.
2113 */
2114
2115 /*
2116 * Queue an OpenID Provider Configuration Request:
2117 *
2118 * https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfigurationRequest
2119 * https://www.rfc-editor.org/rfc/rfc8414#section-3.1
2120 *
2121 * This is done first to get the endpoint URIs we need to contact and to make
2122 * sure the provider provides a device authorization flow. finish_discovery()
2123 * will fill in actx->provider.
2124 */
2125 static bool
2126 start_discovery(struct async_ctx *actx, const char *discovery_uri)
2127 {
2128 CHECK_SETOPT(actx, CURLOPT_HTTPGET, 1L, return false);
2129 CHECK_SETOPT(actx, CURLOPT_URL, discovery_uri, return false);
2130
2131 return start_request(actx);
2132 }
2133
2134 static bool
2135 finish_discovery(struct async_ctx *actx)
2136 {
2137 long response_code;
2138
2139 /*----
2140 * Now check the response. OIDC Discovery 1.0 is pretty strict:
2141 *
2142 * A successful response MUST use the 200 OK HTTP status code and
2143 * return a JSON object using the application/json content type that
2144 * contains a set of Claims as its members that are a subset of the
2145 * Metadata values defined in Section 3.
2146 *
2147 * Compared to standard HTTP semantics, this makes life easy -- we don't
2148 * need to worry about redirections (which would call the Issuer host
2149 * validation into question), or non-authoritative responses, or any other
2150 * complications.
2151 */
2152 CHECK_GETINFO(actx, CURLINFO_RESPONSE_CODE, &response_code, return false);
2153
2154 if (response_code != 200)
2155 {
2156 actx_error(actx, "unexpected response code %ld", response_code);
2157 return false;
2158 }
2159
2160 /*
2161 * Pull the fields we care about from the document.
2162 */
2163 actx->errctx = libpq_gettext("failed to parse OpenID discovery document");
2164 if (!parse_provider(actx, &actx->provider))
2165 return false; /* error message already set */
2166
2167 /*
2168 * Fill in any defaults for OPTIONAL/RECOMMENDED fields we care about.
2169 */
2170 if (!actx->provider.grant_types_supported)
2171 {
2172 /*
2173 * Per Section 3, the default is ["authorization_code", "implicit"].
2174 */
2175 struct curl_slist *temp = actx->provider.grant_types_supported;
2176
2177 temp = curl_slist_append(temp, "authorization_code");
2178 if (temp)
2179 {
2180 temp = curl_slist_append(temp, "implicit");
2181 }
2182
2183 if (!temp)
2184 {
2185 actx_error(actx, "out of memory");
2186 return false;
2187 }
2188
2189 actx->provider.grant_types_supported = temp;
2190 }
2191
2192 return true;
2193 }
2194
2195 /*
2196 * Ensure that the discovery document is provided by the expected issuer.
2197 * Currently, issuers are statically configured in the connection string.
2198 */
2199 static bool
2200 check_issuer(struct async_ctx *actx, PGconn *conn)
2201 {
2202 const struct provider *provider = &actx->provider;
2203 const char *oauth_issuer_id = conn_oauth_issuer_id(conn);
2204
2205 Assert(oauth_issuer_id); /* ensured by setup_oauth_parameters() */
2206 Assert(provider->issuer); /* ensured by parse_provider() */
2207
2208 /*---
2209 * We require strict equality for issuer identifiers -- no path or case
2210 * normalization, no substitution of default ports and schemes, etc. This
2211 * is done to match the rules in OIDC Discovery Sec. 4.3 for config
2212 * validation:
2213 *
2214 * The issuer value returned MUST be identical to the Issuer URL that
2215 * was used as the prefix to /.well-known/openid-configuration to
2216 * retrieve the configuration information.
2217 *
2218 * as well as the rules set out in RFC 9207 for avoiding mix-up attacks:
2219 *
2220 * Clients MUST then [...] compare the result to the issuer identifier
2221 * of the authorization server where the authorization request was
2222 * sent to. This comparison MUST use simple string comparison as defined
2223 * in Section 6.2.1 of [RFC3986].
2224 */
2225 if (strcmp(oauth_issuer_id, provider->issuer) != 0)
2226 {
2227 actx_error(actx,
2228 "the issuer identifier (%s) does not match oauth_issuer (%s)",
2229 provider->issuer, oauth_issuer_id);
2230 return false;
2231 }
2232
2233 return true;
2234 }
2235
2236 #define HTTPS_SCHEME "https://"
2237 #define OAUTH_GRANT_TYPE_DEVICE_CODE "urn:ietf:params:oauth:grant-type:device_code"
2238
2239 /*
2240 * Ensure that the provider supports the Device Authorization flow (i.e. it
2241 * provides an authorization endpoint, and both the token and authorization
2242 * endpoint URLs seem reasonable).
2243 */
2244 static bool
2245 check_for_device_flow(struct async_ctx *actx)
2246 {
2247 const struct provider *provider = &actx->provider;
2248
2249 Assert(provider->issuer); /* ensured by parse_provider() */
2250 Assert(provider->token_endpoint); /* ensured by parse_provider() */
2251
2252 if (!provider->device_authorization_endpoint)
2253 {
2254 actx_error(actx,
2255 "issuer \"%s\" does not provide a device authorization endpoint",
2256 provider->issuer);
2257 return false;
2258 }
2259
2260 /*
2261 * The original implementation checked that OAUTH_GRANT_TYPE_DEVICE_CODE
2262 * was present in the discovery document's grant_types_supported list. MS
2263 * Entra does not advertise this grant type, though, and since it doesn't
2264 * make sense to stand up a device_authorization_endpoint without also
2265 * accepting device codes at the token_endpoint, that's the only thing we
2266 * currently require.
2267 */
2268
2269 /*
2270 * Although libcurl will fail later if the URL contains an unsupported
2271 * scheme, that error message is going to be a bit opaque. This is a
2272 * decent time to bail out if we're not using HTTPS for the endpoints
2273 * we'll use for the flow.
2274 */
2275 if (!actx->debugging)
2276 {
2277 if (pg_strncasecmp(provider->device_authorization_endpoint,
2278 HTTPS_SCHEME, strlen(HTTPS_SCHEME)) != 0)
2279 {
2280 actx_error(actx,
2281 "device authorization endpoint \"%s\" must use HTTPS",
2282 provider->device_authorization_endpoint);
2283 return false;
2284 }
2285
2286 if (pg_strncasecmp(provider->token_endpoint,
2287 HTTPS_SCHEME, strlen(HTTPS_SCHEME)) != 0)
2288 {
2289 actx_error(actx,
2290 "token endpoint \"%s\" must use HTTPS",
2291 provider->token_endpoint);
2292 return false;
2293 }
2294 }
2295
2296 return true;
2297 }
2298
2299 /*
2300 * Adds the client ID (and secret, if provided) to the current request, using
2301 * either HTTP headers or the request body.
2302 */
2303 static bool
2304 add_client_identification(struct async_ctx *actx, PQExpBuffer reqbody, PGconn *conn)
2305 {
2306 const char *oauth_client_id = conn_oauth_client_id(conn);
2307 const char *oauth_client_secret = conn_oauth_client_secret(conn);
2308
2309 bool success = false;
2310 char *username = NULL;
2311 char *password = NULL;
2312
2313 if (oauth_client_secret) /* Zero-length secrets are permitted! */
2314 {
2315 /*----
2316 * Use HTTP Basic auth to send the client_id and secret. Per RFC 6749,
2317 * Sec. 2.3.1,
2318 *
2319 * Including the client credentials in the request-body using the
2320 * two parameters is NOT RECOMMENDED and SHOULD be limited to
2321 * clients unable to directly utilize the HTTP Basic authentication
2322 * scheme (or other password-based HTTP authentication schemes).
2323 *
2324 * Additionally:
2325 *
2326 * The client identifier is encoded using the
2327 * "application/x-www-form-urlencoded" encoding algorithm per Appendix
2328 * B, and the encoded value is used as the username; the client
2329 * password is encoded using the same algorithm and used as the
2330 * password.
2331 *
2332 * (Appendix B modifies application/x-www-form-urlencoded by requiring
2333 * an initial UTF-8 encoding step. Since the client ID and secret must
2334 * both be 7-bit ASCII -- RFC 6749 Appendix A -- we don't worry about
2335 * that in this function.)
2336 *
2337 * client_id is not added to the request body in this case. Not only
2338 * would it be redundant, but some providers in the wild (e.g. Okta)
2339 * refuse to accept it.
2340 */
2341 username = urlencode(oauth_client_id);
2342 password = urlencode(oauth_client_secret);
2343
2344 if (!username || !password)
2345 {
2346 actx_error(actx, "out of memory");
2347 goto cleanup;
2348 }
2349
2350 CHECK_SETOPT(actx, CURLOPT_HTTPAUTH, CURLAUTH_BASIC, goto cleanup);
2351 CHECK_SETOPT(actx, CURLOPT_USERNAME, username, goto cleanup);
2352 CHECK_SETOPT(actx, CURLOPT_PASSWORD, password, goto cleanup);
2353
2354 actx->used_basic_auth = true;
2355 }
2356 else
2357 {
2358 /*
2359 * If we're not otherwise authenticating, client_id is REQUIRED in the
2360 * request body.
2361 */
2362 build_urlencoded(reqbody, "client_id", oauth_client_id);
2363
2364 CHECK_SETOPT(actx, CURLOPT_HTTPAUTH, CURLAUTH_NONE, goto cleanup);
2365 actx->used_basic_auth = false;
2366 }
2367
2368 success = true;
2369
2370 cleanup:
2371 free(username);
2372 free(password);
2373
2374 return success;
2375 }
2376
2377 /*
2378 * Queue a Device Authorization Request:
2379 *
2380 * https://www.rfc-editor.org/rfc/rfc8628#section-3.1
2381 *
2382 * This is the second step. We ask the provider to verify the end user out of
2383 * band and authorize us to act on their behalf; it will give us the required
2384 * nonces for us to later poll the request status, which we'll grab in
2385 * finish_device_authz().
2386 */
2387 static bool
2388 start_device_authz(struct async_ctx *actx, PGconn *conn)
2389 {
2390 const char *oauth_scope = conn_oauth_scope(conn);
2391 const char *device_authz_uri = actx->provider.device_authorization_endpoint;
2392 PQExpBuffer work_buffer = &actx->work_data;
2393
2394 Assert(conn_oauth_client_id(conn)); /* ensured by setup_oauth_parameters() */
2395 Assert(device_authz_uri); /* ensured by check_for_device_flow() */
2396
2397 /* Construct our request body. */
2398 resetPQExpBuffer(work_buffer);
2399 if (oauth_scope && oauth_scope[0])
2400 build_urlencoded(work_buffer, "scope", oauth_scope);
2401
2402 if (!add_client_identification(actx, work_buffer, conn))
2403 return false;
2404
2405 if (PQExpBufferBroken(work_buffer))
2406 {
2407 actx_error(actx, "out of memory");
2408 return false;
2409 }
2410
2411 /* Make our request. */
2412 CHECK_SETOPT(actx, CURLOPT_URL, device_authz_uri, return false);
2413 CHECK_SETOPT(actx, CURLOPT_COPYPOSTFIELDS, work_buffer->data, return false);
2414
2415 return start_request(actx);
2416 }
2417
2418 static bool
2419 finish_device_authz(struct async_ctx *actx)
2420 {
2421 long response_code;
2422
2423 CHECK_GETINFO(actx, CURLINFO_RESPONSE_CODE, &response_code, return false);
2424
2425 /*
2426 * Per RFC 8628, Section 3, a successful device authorization response
2427 * uses 200 OK.
2428 */
2429 if (response_code == 200)
2430 {
2431 actx->errctx = libpq_gettext("failed to parse device authorization");
2432 if (!parse_device_authz(actx, &actx->authz))
2433 return false; /* error message already set */
2434
2435 return true;
2436 }
2437
2438 /*
2439 * The device authorization endpoint uses the same error response as the
2440 * token endpoint, so the error handling roughly follows
2441 * finish_token_request(). The key difference is that an error here is
2442 * immediately fatal.
2443 */
2444 if (response_code == 400 || response_code == 401)
2445 {
2446 struct token_error err = {0};
2447
2448 if (!parse_token_error(actx, &err))
2449 {
2450 free_token_error(&err);
2451 return false;
2452 }
2453
2454 /* Copy the token error into the context error buffer */
2455 record_token_error(actx, &err);
2456
2457 free_token_error(&err);
2458 return false;
2459 }
2460
2461 /* Any other response codes are considered invalid */
2462 actx_error(actx, "unexpected response code %ld", response_code);
2463 return false;
2464 }
2465
2466 /*
2467 * Queue an Access Token Request:
2468 *
2469 * https://www.rfc-editor.org/rfc/rfc6749#section-4.1.3
2470 *
2471 * This is the final step. We continually poll the token endpoint to see if the
2472 * user has authorized us yet. finish_token_request() will pull either the token
2473 * or a (ideally temporary) error status from the provider.
2474 */
2475 static bool
2476 start_token_request(struct async_ctx *actx, PGconn *conn)
2477 {
2478 const char *token_uri = actx->provider.token_endpoint;
2479 const char *device_code = actx->authz.device_code;
2480 PQExpBuffer work_buffer = &actx->work_data;
2481
2482 Assert(conn_oauth_client_id(conn)); /* ensured by setup_oauth_parameters() */
2483 Assert(token_uri); /* ensured by parse_provider() */
2484 Assert(device_code); /* ensured by parse_device_authz() */
2485
2486 /* Construct our request body. */
2487 resetPQExpBuffer(work_buffer);
2488 build_urlencoded(work_buffer, "device_code", device_code);
2489 build_urlencoded(work_buffer, "grant_type", OAUTH_GRANT_TYPE_DEVICE_CODE);
2490
2491 if (!add_client_identification(actx, work_buffer, conn))
2492 return false;
2493
2494 if (PQExpBufferBroken(work_buffer))
2495 {
2496 actx_error(actx, "out of memory");
2497 return false;
2498 }
2499
2500 /* Make our request. */
2501 CHECK_SETOPT(actx, CURLOPT_URL, token_uri, return false);
2502 CHECK_SETOPT(actx, CURLOPT_COPYPOSTFIELDS, work_buffer->data, return false);
2503
2504 return start_request(actx);
2505 }
2506
2507 static bool
2508 finish_token_request(struct async_ctx *actx, struct token *tok)
2509 {
2510 long response_code;
2511
2512 CHECK_GETINFO(actx, CURLINFO_RESPONSE_CODE, &response_code, return false);
2513
2514 /*
2515 * Per RFC 6749, Section 5, a successful response uses 200 OK.
2516 */
2517 if (response_code == 200)
2518 {
2519 actx->errctx = libpq_gettext("failed to parse access token response");
2520 if (!parse_access_token(actx, tok))
2521 return false; /* error message already set */
2522
2523 return true;
2524 }
2525
2526 /*
2527 * An error response uses either 400 Bad Request or 401 Unauthorized.
2528 * There are references online to implementations using 403 for error
2529 * return which would violate the specification. For now we stick to the
2530 * specification but we might have to revisit this.
2531 */
2532 if (response_code == 400 || response_code == 401)
2533 {
2534 if (!parse_token_error(actx, &tok->err))
2535 return false;
2536
2537 return true;
2538 }
2539
2540 /* Any other response codes are considered invalid */
2541 actx_error(actx, "unexpected response code %ld", response_code);
2542 return false;
2543 }
2544
2545 /*
2546 * Finishes the token request and examines the response. If the flow has
2547 * completed, a valid token will be returned via the parameter list. Otherwise,
2548 * the token parameter remains unchanged, and the caller needs to wait for
2549 * another interval (which will have been increased in response to a slow_down
2550 * message from the server) before starting a new token request.
2551 *
2552 * False is returned only for permanent error conditions.
2553 */
2554 static bool
2555 handle_token_response(struct async_ctx *actx, char **token)
2556 {
2557 bool success = false;
2558 struct token tok = {0};
2559 const struct token_error *err;
2560
2561 if (!finish_token_request(actx, &tok))
2562 goto token_cleanup;
2563
2564 /* A successful token request gives either a token or an in-band error. */
2565 Assert(tok.access_token || tok.err.error);
2566
2567 if (tok.access_token)
2568 {
2569 *token = tok.access_token;
2570 tok.access_token = NULL;
2571
2572 success = true;
2573 goto token_cleanup;
2574 }
2575
2576 /*
2577 * authorization_pending and slow_down are the only acceptable errors;
2578 * anything else and we bail. These are defined in RFC 8628, Sec. 3.5.
2579 */
2580 err = &tok.err;
2581 if (strcmp(err->error, "authorization_pending") != 0 &&
2582 strcmp(err->error, "slow_down") != 0)
2583 {
2584 record_token_error(actx, err);
2585 goto token_cleanup;
2586 }
2587
2588 /*
2589 * A slow_down error requires us to permanently increase our retry
2590 * interval by five seconds.
2591 */
2592 if (strcmp(err->error, "slow_down") == 0)
2593 {
2594 if (pg_add_s32_overflow(actx->authz.interval, 5, &actx->authz.interval))
2595 {
2596 actx_error(actx, "slow_down interval overflow");
2597 goto token_cleanup;
2598 }
2599 }
2600
2601 success = true;
2602
2603 token_cleanup:
2604 free_token(&tok);
2605 return success;
2606 }
2607
2608 /*
2609 * Displays a device authorization prompt for action by the end user, either via
2610 * the PQauthDataHook, or by a message on standard error if no hook is set.
2611 */
2612 static bool
2613 prompt_user(struct async_ctx *actx, PGconn *conn)
2614 {
2615 int res;
2616 PGpromptOAuthDevice prompt = {
2617 .verification_uri = actx->authz.verification_uri,
2618 .user_code = actx->authz.user_code,
2619 .verification_uri_complete = actx->authz.verification_uri_complete,
2620 .expires_in = actx->authz.expires_in,
2621 };
2622 PQauthDataHook_type hook = PQgetAuthDataHook();
2623
2624 res = hook(PQAUTHDATA_PROMPT_OAUTH_DEVICE, conn, &prompt);
2625
2626 if (!res)
2627 {
2628 /*
2629 * translator: The first %s is a URL for the user to visit in a
2630 * browser, and the second %s is a code to be copy-pasted there.
2631 */
2632 fprintf(stderr, libpq_gettext("Visit %s and enter the code: %s\n"),
2633 prompt.verification_uri, prompt.user_code);
2634 }
2635 else if (res < 0)
2636 {
2637 actx_error(actx, "device prompt failed");
2638 return false;
2639 }
2640
2641 return true;
2642 }
2643
2644 /*
2645 * Calls curl_global_init() in a thread-safe way.
2646 *
2647 * libcurl has stringent requirements for the thread context in which you call
2648 * curl_global_init(), because it's going to try initializing a bunch of other
2649 * libraries (OpenSSL, Winsock, etc). Recent versions of libcurl have improved
2650 * the thread-safety situation, but there's a chicken-and-egg problem at
2651 * runtime: you can't check the thread safety until you've initialized libcurl,
2652 * which you can't do from within a thread unless you know it's thread-safe...
2653 *
2654 * Returns true if initialization was successful. Successful or not, this
2655 * function will not try to reinitialize Curl on successive calls.
2656 */
2657 static bool
2658 initialize_curl(PGconn *conn)
2659 {
2660 /*
2661 * Don't let the compiler play tricks with this variable. In the
2662 * HAVE_THREADSAFE_CURL_GLOBAL_INIT case, we don't care if two threads
2663 * enter simultaneously, but we do care if this gets set transiently to
2664 * PG_BOOL_YES/NO in cases where that's not the final answer.
2665 */
2666 static volatile PGTernaryBool init_successful = PG_BOOL_UNKNOWN;
2667 curl_version_info_data *info;
2668
2669 #if !HAVE_THREADSAFE_CURL_GLOBAL_INIT
2670
2671 /*
2672 * Lock around the whole function. If a libpq client performs its own work
2673 * with libcurl, it must either ensure that Curl is initialized safely
2674 * before calling us (in which case our call will be a no-op), or else it
2675 * must guard its own calls to curl_global_init() with a registered
2676 * threadlock handler. See PQregisterThreadLock().
2677 */
2678 pglock_thread();
2679 #endif
2680
2681 /*
2682 * Skip initialization if we've already done it. (Curl tracks the number
2683 * of calls; there's no point in incrementing the counter every time we
2684 * connect.)
2685 */
2686 if (init_successful == PG_BOOL_YES)
2687 goto done;
2688 else if (init_successful == PG_BOOL_NO)
2689 {
2690 libpq_append_conn_error(conn,
2691 "curl_global_init previously failed during OAuth setup");
2692 goto done;
2693 }
2694
2695 /*
2696 * We know we've already initialized Winsock by this point (see
2697 * pqMakeEmptyPGconn()), so we should be able to safely skip that bit. But
2698 * we have to tell libcurl to initialize everything else, because other
2699 * pieces of our client executable may already be using libcurl for their
2700 * own purposes. If we initialize libcurl with only a subset of its
2701 * features, we could break those other clients nondeterministically, and
2702 * that would probably be a nightmare to debug.
2703 *
2704 * If some other part of the program has already called this, it's a
2705 * no-op.
2706 */
2707 if (curl_global_init(CURL_GLOBAL_ALL & ~CURL_GLOBAL_WIN32) != CURLE_OK)
2708 {
2709 libpq_append_conn_error(conn,
2710 "curl_global_init failed during OAuth setup");
2711 init_successful = PG_BOOL_NO;
2712 goto done;
2713 }
2714
2715 info = curl_version_info(CURLVERSION_NOW);
2716
2717 #if HAVE_THREADSAFE_CURL_GLOBAL_INIT
2718
2719 /*
2720 * If we determined at configure time that the Curl installation is
2721 * thread-safe, our job here is much easier. We simply initialize above
2722 * without any locking (concurrent or duplicated calls are fine in that
2723 * situation), then double-check to make sure the runtime setting agrees,
2724 * to try to catch silent downgrades.
2725 */
2726 if (!(info->features & CURL_VERSION_THREADSAFE))
2727 {
2728 /*
2729 * In a downgrade situation, the damage is already done. Curl global
2730 * state may be corrupted. Be noisy.
2731 */
2732 libpq_append_conn_error(conn, "libcurl is no longer thread-safe\n"
2733 "\tCurl initialization was reported thread-safe when libpq\n"
2734 "\twas compiled, but the currently installed version of\n"
2735 "\tlibcurl reports that it is not. Recompile libpq against\n"
2736 "\tthe installed version of libcurl.");
2737 init_successful = PG_BOOL_NO;
2738 goto done;
2739 }
2740 #endif
2741
2742 if (oauth_unsafe_debugging_enabled())
2743 {
2744 /*
2745 * Record the version of libcurl and its SSL library when tracing,
2746 * since those are likely to be relevant to network debugging. Neither
2747 * of these strings should be NULL in a useful installation, but
2748 * that's no reason to crash if they are, so provide fallbacks.
2749 *
2750 * Other Curl dependency info might be helpful in the future, too;
2751 * just be sure to check info->age as needed when adding more.
2752 */
2753 fprintf(stderr, "[libpq] initialized libcurl %s (%s)\n",
2754 info->version ? info->version : "version unknown",
2755 info->ssl_version ? info->ssl_version : "no SSL");
2756 }
2757
2758 init_successful = PG_BOOL_YES;
2759
2760 done:
2761 #if !HAVE_THREADSAFE_CURL_GLOBAL_INIT
2762 pgunlock_thread();
2763 #endif
2764 return (init_successful == PG_BOOL_YES);
2765 }
2766
2767 /*
2768 * The core nonblocking libcurl implementation. This will be called several
2769 * times to pump the async engine.
2770 *
2771 * The architecture is based on PQconnectPoll(). The first half drives the
2772 * connection state forward as necessary, returning if we're not ready to
2773 * proceed to the next step yet. The second half performs the actual transition
2774 * between states.
2775 *
2776 * You can trace the overall OAuth flow through the second half. It's linear
2777 * until we get to the end, where we flip back and forth between
2778 * OAUTH_STEP_TOKEN_REQUEST and OAUTH_STEP_WAIT_INTERVAL to regularly ping the
2779 * provider.
2780 */
2781 static PostgresPollingStatusType
2782 pg_fe_run_oauth_flow_impl(PGconn *conn)
2783 {
2784 fe_oauth_state *state = conn_sasl_state(conn);
2785 struct async_ctx *actx;
2786 char *oauth_token = NULL;
2787 PQExpBuffer errbuf;
2788
2789 if (!initialize_curl(conn))
2790 return PGRES_POLLING_FAILED;
2791
2792 if (!state->async_ctx)
2793 {
2794 /*
2795 * Create our asynchronous state, and hook it into the upper-level
2796 * OAuth state immediately, so any failures below won't leak the
2797 * context allocation.
2798 */
2799 actx = calloc(1, sizeof(*actx));
2800 if (!actx)
2801 {
2802 libpq_append_conn_error(conn, "out of memory");
2803 return PGRES_POLLING_FAILED;
2804 }
2805
2806 actx->mux = PGINVALID_SOCKET;
2807 actx->timerfd = -1;
2808
2809 /* Should we enable unsafe features? */
2810 actx->debugging = oauth_unsafe_debugging_enabled();
2811
2812 state->async_ctx = actx;
2813
2814 initPQExpBuffer(&actx->work_data);
2815 initPQExpBuffer(&actx->errbuf);
2816
2817 if (!setup_multiplexer(actx))
2818 goto error_return;
2819
2820 if (!setup_curl_handles(actx))
2821 goto error_return;
2822 }
2823
2824 actx = state->async_ctx;
2825
2826 do
2827 {
2828 /* By default, the multiplexer is the altsock. Reassign as desired. */
2829 set_conn_altsock(conn, actx->mux);
2830
2831 switch (actx->step)
2832 {
2833 case OAUTH_STEP_INIT:
2834 break;
2835
2836 case OAUTH_STEP_DISCOVERY:
2837 case OAUTH_STEP_DEVICE_AUTHORIZATION:
2838 case OAUTH_STEP_TOKEN_REQUEST:
2839 {
2840 PostgresPollingStatusType status;
2841
2842 /*
2843 * Clear any expired timeout before calling back into
2844 * Curl. Curl is not guaranteed to do this for us, because
2845 * its API expects us to use single-shot (i.e.
2846 * edge-triggered) timeouts, and ours are level-triggered
2847 * via the mux.
2848 *
2849 * This can't be combined with the comb_multiplexer() call
2850 * below: we might accidentally clear a short timeout that
2851 * was both set and expired during the call to
2852 * drive_request().
2853 */
2854 if (!drain_timer_events(actx, NULL))
2855 goto error_return;
2856
2857 /* Move the request forward. */
2858 status = drive_request(actx);
2859
2860 if (status == PGRES_POLLING_FAILED)
2861 goto error_return;
2862 else if (status == PGRES_POLLING_OK)
2863 break; /* done! */
2864
2865 /*
2866 * This request is still running.
2867 *
2868 * Make sure that stale events don't cause us to come back
2869 * early. (Currently, this can occur only with kqueue.) If
2870 * this is forgotten, the multiplexer can get stuck in a
2871 * signaled state and we'll burn CPU cycles pointlessly.
2872 */
2873 if (!comb_multiplexer(actx))
2874 goto error_return;
2875
2876 return status;
2877 }
2878
2879 case OAUTH_STEP_WAIT_INTERVAL:
2880 {
2881 bool expired;
2882
2883 /*
2884 * The client application is supposed to wait until our
2885 * timer expires before calling PQconnectPoll() again, but
2886 * that might not happen. To avoid sending a token request
2887 * early, check the timer before continuing.
2888 */
2889 if (!drain_timer_events(actx, &expired))
2890 goto error_return;
2891
2892 if (!expired)
2893 {
2894 set_conn_altsock(conn, actx->timerfd);
2895 return PGRES_POLLING_READING;
2896 }
2897
2898 break;
2899 }
2900 }
2901
2902 /*
2903 * Each case here must ensure that actx->running is set while we're
2904 * waiting on some asynchronous work. Most cases rely on
2905 * start_request() to do that for them.
2906 */
2907 switch (actx->step)
2908 {
2909 case OAUTH_STEP_INIT:
2910 actx->errctx = libpq_gettext("failed to fetch OpenID discovery document");
2911 if (!start_discovery(actx, conn_oauth_discovery_uri(conn)))
2912 goto error_return;
2913
2914 actx->step = OAUTH_STEP_DISCOVERY;
2915 break;
2916
2917 case OAUTH_STEP_DISCOVERY:
2918 if (!finish_discovery(actx))
2919 goto error_return;
2920
2921 if (!check_issuer(actx, conn))
2922 goto error_return;
2923
2924 actx->errctx = libpq_gettext("cannot run OAuth device authorization");
2925 if (!check_for_device_flow(actx))
2926 goto error_return;
2927
2928 actx->errctx = libpq_gettext("failed to obtain device authorization");
2929 if (!start_device_authz(actx, conn))
2930 goto error_return;
2931
2932 actx->step = OAUTH_STEP_DEVICE_AUTHORIZATION;
2933 break;
2934
2935 case OAUTH_STEP_DEVICE_AUTHORIZATION:
2936 if (!finish_device_authz(actx))
2937 goto error_return;
2938
2939 actx->errctx = libpq_gettext("failed to obtain access token");
2940 if (!start_token_request(actx, conn))
2941 goto error_return;
2942
2943 actx->step = OAUTH_STEP_TOKEN_REQUEST;
2944 break;
2945
2946 case OAUTH_STEP_TOKEN_REQUEST:
2947 if (!handle_token_response(actx, &oauth_token))
2948 goto error_return;
2949
2950 /*
2951 * Hook any oauth_token into the PGconn immediately so that
2952 * the allocation isn't lost in case of an error.
2953 */
2954 set_conn_oauth_token(conn, oauth_token);
2955
2956 if (!actx->user_prompted)
2957 {
2958 /*
2959 * Now that we know the token endpoint isn't broken, give
2960 * the user the login instructions.
2961 */
2962 if (!prompt_user(actx, conn))
2963 goto error_return;
2964
2965 actx->user_prompted = true;
2966 }
2967
2968 if (oauth_token)
2969 break; /* done! */
2970
2971 /*
2972 * Wait for the required interval before issuing the next
2973 * request.
2974 */
2975 {
2976 /*
2977 * Avoid overflow of long int. (By the time we reach
2978 * LONG_MAX milliseconds -- 24 days on 32-bit platforms --
2979 * continuing to honor slow_down requests seems pretty
2980 * pointless anyway.)
2981 */
2982 int64 interval_ms;
2983
2984 if (pg_mul_s64_overflow(actx->authz.interval, 1000,
2985 &interval_ms)
2986 || (interval_ms > LONG_MAX))
2987 {
2988 interval_ms = LONG_MAX;
2989 }
2990
2991 if (!set_timer(actx, (long) interval_ms))
2992 goto error_return;
2993 }
2994
2995 /*
2996 * No Curl requests are running, so we can simplify by having
2997 * the client wait directly on the timerfd rather than the
2998 * multiplexer.
2999 */
3000 set_conn_altsock(conn, actx->timerfd);
3001
3002 actx->step = OAUTH_STEP_WAIT_INTERVAL;
3003 actx->running = 1;
3004 break;
3005
3006 case OAUTH_STEP_WAIT_INTERVAL:
3007 actx->errctx = libpq_gettext("failed to obtain access token");
3008 if (!start_token_request(actx, conn))
3009 goto error_return;
3010
3011 actx->step = OAUTH_STEP_TOKEN_REQUEST;
3012 break;
3013 }
3014
3015 /*
3016 * The vast majority of the time, if we don't have a token at this
3017 * point, actx->running will be set. But there are some corner cases
3018 * where we can immediately loop back around; see start_request().
3019 */
3020 } while (!oauth_token && !actx->running);
3021
3022 /* If we've stored a token, we're done. Otherwise come back later. */
3023 return oauth_token ? PGRES_POLLING_OK : PGRES_POLLING_READING;
3024
3025 error_return:
3026 errbuf = conn_errorMessage(conn);
3027
3028 /*
3029 * Assemble the three parts of our error: context, body, and detail. See
3030 * also the documentation for struct async_ctx.
3031 */
3032 if (actx->errctx)
3033 appendPQExpBuffer(errbuf, "%s: ", actx->errctx);
3034
3035 if (PQExpBufferDataBroken(actx->errbuf))
3036 appendPQExpBufferStr(errbuf, libpq_gettext("out of memory"));
3037 else
3038 appendPQExpBufferStr(errbuf, actx->errbuf.data);
3039
3040 if (actx->curl_err[0])
3041 {
3042 appendPQExpBuffer(errbuf, " (libcurl: %s)", actx->curl_err);
3043
3044 /* Sometimes libcurl adds a newline to the error buffer. :( */
3045 if (errbuf->len >= 2 && errbuf->data[errbuf->len - 2] == '\n')
3046 {
3047 errbuf->data[errbuf->len - 2] = ')';
3048 errbuf->data[errbuf->len - 1] = '\0';
3049 errbuf->len--;
3050 }
3051 }
3052
3053 appendPQExpBufferChar(errbuf, '\n');
3054
3055 return PGRES_POLLING_FAILED;
3056 }
3057
3058 /*
3059 * The top-level entry point. This is a convenient place to put necessary
3060 * wrapper logic before handing off to the true implementation, above.
3061 */
3062 PostgresPollingStatusType
3063 pg_fe_run_oauth_flow(PGconn *conn)
3064 {
3065 PostgresPollingStatusType result;
3066 fe_oauth_state *state = conn_sasl_state(conn);
3067 struct async_ctx *actx;
3068 #ifndef WIN32
3069 sigset_t osigset;
3070 bool sigpipe_pending;
3071 bool masked;
3072
3073 /*---
3074 * Ignore SIGPIPE on this thread during all Curl processing.
3075 *
3076 * Because we support multiple threads, we have to set up libcurl with
3077 * CURLOPT_NOSIGNAL, which disables its default global handling of
3078 * SIGPIPE. From the Curl docs:
3079 *
3080 * libcurl makes an effort to never cause such SIGPIPE signals to
3081 * trigger, but some operating systems have no way to avoid them and
3082 * even on those that have there are some corner cases when they may
3083 * still happen, contrary to our desire.
3084 *
3085 * Note that libcurl is also at the mercy of its DNS resolution and SSL
3086 * libraries; if any of them forget a MSG_NOSIGNAL then we're in trouble.
3087 * Modern platforms and libraries seem to get it right, so this is a
3088 * difficult corner case to exercise in practice, and unfortunately it's
3089 * not really clear whether it's necessary in all cases.
3090 */
3091 masked = (pq_block_sigpipe(&osigset, &sigpipe_pending) == 0);
3092 #endif
3093
3094 result = pg_fe_run_oauth_flow_impl(conn);
3095
3096 /*
3097 * To assist with finding bugs in comb_multiplexer() and
3098 * drain_timer_events(), when we're in debug mode, track the total number
3099 * of calls to this function and print that at the end of the flow.
3100 *
3101 * Be careful that state->async_ctx could be NULL if early initialization
3102 * fails during the first call.
3103 */
3104 actx = state->async_ctx;
3105 Assert(actx || result == PGRES_POLLING_FAILED);
3106
3107 if (actx && actx->debugging)
3108 {
3109 actx->dbg_num_calls++;
3110 if (result == PGRES_POLLING_OK || result == PGRES_POLLING_FAILED)
3111 fprintf(stderr, "[libpq] total number of polls: %d\n",
3112 actx->dbg_num_calls);
3113 }
3114
3115 #ifndef WIN32
3116 if (masked)
3117 {
3118 /*
3119 * Undo the SIGPIPE mask. Assume we may have gotten EPIPE (we have no
3120 * way of knowing at this level).
3121 */
3122 pq_reset_sigpipe(&osigset, sigpipe_pending, true /* EPIPE, maybe */ );
3123 }
3124 #endif
3125
3126 return result;
3127 }