Thanks to visit codestin.com
Credit goes to doxygen.postgresql.org

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