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 * Add another macro layer that inserts the needed semicolon, to avoid having
1924 * to write a literal semicolon in the call below, which would break pgindent.
1925 */
1926#define PG_CURL_IGNORE_DEPRECATION(x) CURL_IGNORE_DEPRECATION(x;)
1927
1928/*
1929 * Drives the multi handle towards completion. The caller should have already
1930 * set up an asynchronous request via start_request().
1931 */
1934{
1935 CURLMcode err;
1936 CURLMsg *msg;
1937 int msgs_left;
1938 bool done;
1939
1940 if (actx->running)
1941 {
1942 /*---
1943 * There's an async request in progress. Pump the multi handle.
1944 *
1945 * curl_multi_socket_all() is officially deprecated, because it's
1946 * inefficient and pointless if your event loop has already handed you
1947 * the exact sockets that are ready. But that's not our use case --
1948 * our client has no way to tell us which sockets are ready. (They
1949 * don't even know there are sockets to begin with.)
1950 *
1951 * We can grab the list of triggered events from the multiplexer
1952 * ourselves, but that's effectively what curl_multi_socket_all() is
1953 * going to do. And there are currently no plans for the Curl project
1954 * to remove or break this API, so ignore the deprecation. See
1955 *
1956 * https://curl.se/mail/lib-2024-11/0028.html
1957 */
1959 curl_multi_socket_all(actx->curlm,
1960 &actx->running));
1961
1962 if (err)
1963 {
1964 actx_error(actx, "asynchronous HTTP request failed: %s",
1965 curl_multi_strerror(err));
1966 return PGRES_POLLING_FAILED;
1967 }
1968
1969 if (actx->running)
1970 {
1971 /* We'll come back again. */
1972 return PGRES_POLLING_READING;
1973 }
1974 }
1975
1976 done = false;
1977 while ((msg = curl_multi_info_read(actx->curlm, &msgs_left)) != NULL)
1978 {
1979 if (msg->msg != CURLMSG_DONE)
1980 {
1981 /*
1982 * Future libcurl versions may define new message types; we don't
1983 * know how to handle them, so we'll ignore them.
1984 */
1985 continue;
1986 }
1987
1988 /* First check the status of the request itself. */
1989 if (msg->data.result != CURLE_OK)
1990 {
1991 /*
1992 * If a more specific error hasn't already been reported, use
1993 * libcurl's description.
1994 */
1995 if (actx->errbuf.len == 0)
1996 actx_error_str(actx, curl_easy_strerror(msg->data.result));
1997
1998 return PGRES_POLLING_FAILED;
1999 }
2000
2001 /* Now remove the finished handle; we'll add it back later if needed. */
2002 err = curl_multi_remove_handle(actx->curlm, msg->easy_handle);
2003 if (err)
2004 {
2005 actx_error(actx, "libcurl easy handle removal failed: %s",
2006 curl_multi_strerror(err));
2007 return PGRES_POLLING_FAILED;
2008 }
2009
2010 done = true;
2011 }
2012
2013 /* Sanity check. */
2014 if (!done)
2015 {
2016 actx_error(actx, "no result was retrieved for the finished handle");
2017 return PGRES_POLLING_FAILED;
2018 }
2019
2020 return PGRES_POLLING_OK;
2021}
2022
2023/*
2024 * URL-Encoding Helpers
2025 */
2026
2027/*
2028 * Encodes a string using the application/x-www-form-urlencoded format, and
2029 * appends it to the given buffer.
2030 */
2031static void
2033{
2034 char *escaped;
2035 char *haystack;
2036 char *match;
2037
2038 /* The first parameter to curl_easy_escape is deprecated by Curl */
2039 escaped = curl_easy_escape(NULL, s, 0);
2040 if (!escaped)
2041 {
2042 termPQExpBuffer(buf); /* mark the buffer broken */
2043 return;
2044 }
2045
2046 /*
2047 * curl_easy_escape() almost does what we want, but we need the
2048 * query-specific flavor which uses '+' instead of '%20' for spaces. The
2049 * Curl command-line tool does this with a simple search-and-replace, so
2050 * follow its lead.
2051 */
2052 haystack = escaped;
2053
2054 while ((match = strstr(haystack, "%20")) != NULL)
2055 {
2056 /* Append the unmatched portion, followed by the plus sign. */
2057 appendBinaryPQExpBuffer(buf, haystack, match - haystack);
2059
2060 /* Keep searching after the match. */
2061 haystack = match + 3 /* strlen("%20") */ ;
2062 }
2063
2064 /* Push the remainder of the string onto the buffer. */
2065 appendPQExpBufferStr(buf, haystack);
2066
2067 curl_free(escaped);
2068}
2069
2070/*
2071 * Convenience wrapper for encoding a single string. Returns NULL on allocation
2072 * failure.
2073 */
2074static char *
2075urlencode(const char *s)
2076{
2078
2081
2082 return PQExpBufferDataBroken(buf) ? NULL : buf.data;
2083}
2084
2085/*
2086 * Appends a key/value pair to the end of an application/x-www-form-urlencoded
2087 * list.
2088 */
2089static void
2090build_urlencoded(PQExpBuffer buf, const char *key, const char *value)
2091{
2092 if (buf->len)
2094
2098}
2099
2100/*
2101 * Specific HTTP Request Handlers
2102 *
2103 * This is finally the beginning of the actual application logic. Generally
2104 * speaking, a single request consists of a start_* and a finish_* step, with
2105 * drive_request() pumping the machine in between.
2106 */
2107
2108/*
2109 * Queue an OpenID Provider Configuration Request:
2110 *
2111 * https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfigurationRequest
2112 * https://www.rfc-editor.org/rfc/rfc8414#section-3.1
2113 *
2114 * This is done first to get the endpoint URIs we need to contact and to make
2115 * sure the provider provides a device authorization flow. finish_discovery()
2116 * will fill in actx->provider.
2117 */
2118static bool
2119start_discovery(struct async_ctx *actx, const char *discovery_uri)
2120{
2121 CHECK_SETOPT(actx, CURLOPT_HTTPGET, 1L, return false);
2122 CHECK_SETOPT(actx, CURLOPT_URL, discovery_uri, return false);
2123
2124 return start_request(actx);
2125}
2126
2127static bool
2129{
2130 long response_code;
2131
2132 /*----
2133 * Now check the response. OIDC Discovery 1.0 is pretty strict:
2134 *
2135 * A successful response MUST use the 200 OK HTTP status code and
2136 * return a JSON object using the application/json content type that
2137 * contains a set of Claims as its members that are a subset of the
2138 * Metadata values defined in Section 3.
2139 *
2140 * Compared to standard HTTP semantics, this makes life easy -- we don't
2141 * need to worry about redirections (which would call the Issuer host
2142 * validation into question), or non-authoritative responses, or any other
2143 * complications.
2144 */
2145 CHECK_GETINFO(actx, CURLINFO_RESPONSE_CODE, &response_code, return false);
2146
2147 if (response_code != 200)
2148 {
2149 actx_error(actx, "unexpected response code %ld", response_code);
2150 return false;
2151 }
2152
2153 /*
2154 * Pull the fields we care about from the document.
2155 */
2156 actx->errctx = "failed to parse OpenID discovery document";
2157 if (!parse_provider(actx, &actx->provider))
2158 return false; /* error message already set */
2159
2160 /*
2161 * Fill in any defaults for OPTIONAL/RECOMMENDED fields we care about.
2162 */
2164 {
2165 /*
2166 * Per Section 3, the default is ["authorization_code", "implicit"].
2167 */
2168 struct curl_slist *temp = actx->provider.grant_types_supported;
2169
2170 temp = curl_slist_append(temp, "authorization_code");
2171 if (temp)
2172 {
2173 temp = curl_slist_append(temp, "implicit");
2174 }
2175
2176 if (!temp)
2177 {
2178 actx_error(actx, "out of memory");
2179 return false;
2180 }
2181
2182 actx->provider.grant_types_supported = temp;
2183 }
2184
2185 return true;
2186}
2187
2188/*
2189 * Ensure that the discovery document is provided by the expected issuer.
2190 * Currently, issuers are statically configured in the connection string.
2191 */
2192static bool
2194{
2195 const struct provider *provider = &actx->provider;
2196 const char *oauth_issuer_id = conn_oauth_issuer_id(conn);
2197
2198 Assert(oauth_issuer_id); /* ensured by setup_oauth_parameters() */
2199 Assert(provider->issuer); /* ensured by parse_provider() */
2200
2201 /*---
2202 * We require strict equality for issuer identifiers -- no path or case
2203 * normalization, no substitution of default ports and schemes, etc. This
2204 * is done to match the rules in OIDC Discovery Sec. 4.3 for config
2205 * validation:
2206 *
2207 * The issuer value returned MUST be identical to the Issuer URL that
2208 * was used as the prefix to /.well-known/openid-configuration to
2209 * retrieve the configuration information.
2210 *
2211 * as well as the rules set out in RFC 9207 for avoiding mix-up attacks:
2212 *
2213 * Clients MUST then [...] compare the result to the issuer identifier
2214 * of the authorization server where the authorization request was
2215 * sent to. This comparison MUST use simple string comparison as defined
2216 * in Section 6.2.1 of [RFC3986].
2217 */
2218 if (strcmp(oauth_issuer_id, provider->issuer) != 0)
2219 {
2220 actx_error(actx,
2221 "the issuer identifier (%s) does not match oauth_issuer (%s)",
2222 provider->issuer, oauth_issuer_id);
2223 return false;
2224 }
2225
2226 return true;
2227}
2228
2229#define HTTPS_SCHEME "https://"
2230#define OAUTH_GRANT_TYPE_DEVICE_CODE "urn:ietf:params:oauth:grant-type:device_code"
2231
2232/*
2233 * Ensure that the provider supports the Device Authorization flow (i.e. it
2234 * provides an authorization endpoint, and both the token and authorization
2235 * endpoint URLs seem reasonable).
2236 */
2237static bool
2239{
2240 const struct provider *provider = &actx->provider;
2241
2242 Assert(provider->issuer); /* ensured by parse_provider() */
2243 Assert(provider->token_endpoint); /* ensured by parse_provider() */
2244
2246 {
2247 actx_error(actx,
2248 "issuer \"%s\" does not provide a device authorization endpoint",
2249 provider->issuer);
2250 return false;
2251 }
2252
2253 /*
2254 * The original implementation checked that OAUTH_GRANT_TYPE_DEVICE_CODE
2255 * was present in the discovery document's grant_types_supported list. MS
2256 * Entra does not advertise this grant type, though, and since it doesn't
2257 * make sense to stand up a device_authorization_endpoint without also
2258 * accepting device codes at the token_endpoint, that's the only thing we
2259 * currently require.
2260 */
2261
2262 /*
2263 * Although libcurl will fail later if the URL contains an unsupported
2264 * scheme, that error message is going to be a bit opaque. This is a
2265 * decent time to bail out if we're not using HTTPS for the endpoints
2266 * we'll use for the flow.
2267 */
2268 if (!actx->debugging)
2269 {
2271 HTTPS_SCHEME, strlen(HTTPS_SCHEME)) != 0)
2272 {
2273 actx_error(actx,
2274 "device authorization endpoint \"%s\" must use HTTPS",
2276 return false;
2277 }
2278
2280 HTTPS_SCHEME, strlen(HTTPS_SCHEME)) != 0)
2281 {
2282 actx_error(actx,
2283 "token endpoint \"%s\" must use HTTPS",
2285 return false;
2286 }
2287 }
2288
2289 return true;
2290}
2291
2292/*
2293 * Adds the client ID (and secret, if provided) to the current request, using
2294 * either HTTP headers or the request body.
2295 */
2296static bool
2298{
2299 const char *oauth_client_id = conn_oauth_client_id(conn);
2300 const char *oauth_client_secret = conn_oauth_client_secret(conn);
2301
2302 bool success = false;
2303 char *username = NULL;
2304 char *password = NULL;
2305
2306 if (oauth_client_secret) /* Zero-length secrets are permitted! */
2307 {
2308 /*----
2309 * Use HTTP Basic auth to send the client_id and secret. Per RFC 6749,
2310 * Sec. 2.3.1,
2311 *
2312 * Including the client credentials in the request-body using the
2313 * two parameters is NOT RECOMMENDED and SHOULD be limited to
2314 * clients unable to directly utilize the HTTP Basic authentication
2315 * scheme (or other password-based HTTP authentication schemes).
2316 *
2317 * Additionally:
2318 *
2319 * The client identifier is encoded using the
2320 * "application/x-www-form-urlencoded" encoding algorithm per Appendix
2321 * B, and the encoded value is used as the username; the client
2322 * password is encoded using the same algorithm and used as the
2323 * password.
2324 *
2325 * (Appendix B modifies application/x-www-form-urlencoded by requiring
2326 * an initial UTF-8 encoding step. Since the client ID and secret must
2327 * both be 7-bit ASCII -- RFC 6749 Appendix A -- we don't worry about
2328 * that in this function.)
2329 *
2330 * client_id is not added to the request body in this case. Not only
2331 * would it be redundant, but some providers in the wild (e.g. Okta)
2332 * refuse to accept it.
2333 */
2334 username = urlencode(oauth_client_id);
2335 password = urlencode(oauth_client_secret);
2336
2337 if (!username || !password)
2338 {
2339 actx_error(actx, "out of memory");
2340 goto cleanup;
2341 }
2342
2343 CHECK_SETOPT(actx, CURLOPT_HTTPAUTH, CURLAUTH_BASIC, goto cleanup);
2344 CHECK_SETOPT(actx, CURLOPT_USERNAME, username, goto cleanup);
2345 CHECK_SETOPT(actx, CURLOPT_PASSWORD, password, goto cleanup);
2346
2347 actx->used_basic_auth = true;
2348 }
2349 else
2350 {
2351 /*
2352 * If we're not otherwise authenticating, client_id is REQUIRED in the
2353 * request body.
2354 */
2355 build_urlencoded(reqbody, "client_id", oauth_client_id);
2356
2357 CHECK_SETOPT(actx, CURLOPT_HTTPAUTH, CURLAUTH_NONE, goto cleanup);
2358 actx->used_basic_auth = false;
2359 }
2360
2361 success = true;
2362
2363cleanup:
2364 free(username);
2365 free(password);
2366
2367 return success;
2368}
2369
2370/*
2371 * Queue a Device Authorization Request:
2372 *
2373 * https://www.rfc-editor.org/rfc/rfc8628#section-3.1
2374 *
2375 * This is the second step. We ask the provider to verify the end user out of
2376 * band and authorize us to act on their behalf; it will give us the required
2377 * nonces for us to later poll the request status, which we'll grab in
2378 * finish_device_authz().
2379 */
2380static bool
2382{
2383 const char *oauth_scope = conn_oauth_scope(conn);
2384 const char *device_authz_uri = actx->provider.device_authorization_endpoint;
2385 PQExpBuffer work_buffer = &actx->work_data;
2386
2387 Assert(conn_oauth_client_id(conn)); /* ensured by setup_oauth_parameters() */
2388 Assert(device_authz_uri); /* ensured by check_for_device_flow() */
2389
2390 /* Construct our request body. */
2391 resetPQExpBuffer(work_buffer);
2392 if (oauth_scope && oauth_scope[0])
2393 build_urlencoded(work_buffer, "scope", oauth_scope);
2394
2395 if (!add_client_identification(actx, work_buffer, conn))
2396 return false;
2397
2398 if (PQExpBufferBroken(work_buffer))
2399 {
2400 actx_error(actx, "out of memory");
2401 return false;
2402 }
2403
2404 /* Make our request. */
2405 CHECK_SETOPT(actx, CURLOPT_URL, device_authz_uri, return false);
2406 CHECK_SETOPT(actx, CURLOPT_COPYPOSTFIELDS, work_buffer->data, return false);
2407
2408 return start_request(actx);
2409}
2410
2411static bool
2413{
2414 long response_code;
2415
2416 CHECK_GETINFO(actx, CURLINFO_RESPONSE_CODE, &response_code, return false);
2417
2418 /*
2419 * Per RFC 8628, Section 3, a successful device authorization response
2420 * uses 200 OK.
2421 */
2422 if (response_code == 200)
2423 {
2424 actx->errctx = "failed to parse device authorization";
2425 if (!parse_device_authz(actx, &actx->authz))
2426 return false; /* error message already set */
2427
2428 return true;
2429 }
2430
2431 /*
2432 * The device authorization endpoint uses the same error response as the
2433 * token endpoint, so the error handling roughly follows
2434 * finish_token_request(). The key difference is that an error here is
2435 * immediately fatal.
2436 */
2437 if (response_code == 400 || response_code == 401)
2438 {
2439 struct token_error err = {0};
2440
2441 if (!parse_token_error(actx, &err))
2442 {
2444 return false;
2445 }
2446
2447 /* Copy the token error into the context error buffer */
2448 record_token_error(actx, &err);
2449
2451 return false;
2452 }
2453
2454 /* Any other response codes are considered invalid */
2455 actx_error(actx, "unexpected response code %ld", response_code);
2456 return false;
2457}
2458
2459/*
2460 * Queue an Access Token Request:
2461 *
2462 * https://www.rfc-editor.org/rfc/rfc6749#section-4.1.3
2463 *
2464 * This is the final step. We continually poll the token endpoint to see if the
2465 * user has authorized us yet. finish_token_request() will pull either the token
2466 * or a (ideally temporary) error status from the provider.
2467 */
2468static bool
2470{
2471 const char *token_uri = actx->provider.token_endpoint;
2472 const char *device_code = actx->authz.device_code;
2473 PQExpBuffer work_buffer = &actx->work_data;
2474
2475 Assert(conn_oauth_client_id(conn)); /* ensured by setup_oauth_parameters() */
2476 Assert(token_uri); /* ensured by parse_provider() */
2477 Assert(device_code); /* ensured by parse_device_authz() */
2478
2479 /* Construct our request body. */
2480 resetPQExpBuffer(work_buffer);
2481 build_urlencoded(work_buffer, "device_code", device_code);
2482 build_urlencoded(work_buffer, "grant_type", OAUTH_GRANT_TYPE_DEVICE_CODE);
2483
2484 if (!add_client_identification(actx, work_buffer, conn))
2485 return false;
2486
2487 if (PQExpBufferBroken(work_buffer))
2488 {
2489 actx_error(actx, "out of memory");
2490 return false;
2491 }
2492
2493 /* Make our request. */
2494 CHECK_SETOPT(actx, CURLOPT_URL, token_uri, return false);
2495 CHECK_SETOPT(actx, CURLOPT_COPYPOSTFIELDS, work_buffer->data, return false);
2496
2497 return start_request(actx);
2498}
2499
2500static bool
2501finish_token_request(struct async_ctx *actx, struct token *tok)
2502{
2503 long response_code;
2504
2505 CHECK_GETINFO(actx, CURLINFO_RESPONSE_CODE, &response_code, return false);
2506
2507 /*
2508 * Per RFC 6749, Section 5, a successful response uses 200 OK.
2509 */
2510 if (response_code == 200)
2511 {
2512 actx->errctx = "failed to parse access token response";
2513 if (!parse_access_token(actx, tok))
2514 return false; /* error message already set */
2515
2516 return true;
2517 }
2518
2519 /*
2520 * An error response uses either 400 Bad Request or 401 Unauthorized.
2521 * There are references online to implementations using 403 for error
2522 * return which would violate the specification. For now we stick to the
2523 * specification but we might have to revisit this.
2524 */
2525 if (response_code == 400 || response_code == 401)
2526 {
2527 if (!parse_token_error(actx, &tok->err))
2528 return false;
2529
2530 return true;
2531 }
2532
2533 /* Any other response codes are considered invalid */
2534 actx_error(actx, "unexpected response code %ld", response_code);
2535 return false;
2536}
2537
2538/*
2539 * Finishes the token request and examines the response. If the flow has
2540 * completed, a valid token will be returned via the parameter list. Otherwise,
2541 * the token parameter remains unchanged, and the caller needs to wait for
2542 * another interval (which will have been increased in response to a slow_down
2543 * message from the server) before starting a new token request.
2544 *
2545 * False is returned only for permanent error conditions.
2546 */
2547static bool
2549{
2550 bool success = false;
2551 struct token tok = {0};
2552 const struct token_error *err;
2553
2554 if (!finish_token_request(actx, &tok))
2555 goto token_cleanup;
2556
2557 /* A successful token request gives either a token or an in-band error. */
2558 Assert(tok.access_token || tok.err.error);
2559
2560 if (tok.access_token)
2561 {
2562 *token = tok.access_token;
2563 tok.access_token = NULL;
2564
2565 success = true;
2566 goto token_cleanup;
2567 }
2568
2569 /*
2570 * authorization_pending and slow_down are the only acceptable errors;
2571 * anything else and we bail. These are defined in RFC 8628, Sec. 3.5.
2572 */
2573 err = &tok.err;
2574 if (strcmp(err->error, "authorization_pending") != 0 &&
2575 strcmp(err->error, "slow_down") != 0)
2576 {
2577 record_token_error(actx, err);
2578 goto token_cleanup;
2579 }
2580
2581 /*
2582 * A slow_down error requires us to permanently increase our retry
2583 * interval by five seconds.
2584 */
2585 if (strcmp(err->error, "slow_down") == 0)
2586 {
2587 int prev_interval = actx->authz.interval;
2588
2589 actx->authz.interval += 5;
2590 if (actx->authz.interval < prev_interval)
2591 {
2592 actx_error(actx, "slow_down interval overflow");
2593 goto token_cleanup;
2594 }
2595 }
2596
2597 success = true;
2598
2599token_cleanup:
2600 free_token(&tok);
2601 return success;
2602}
2603
2604/*
2605 * Displays a device authorization prompt for action by the end user, either via
2606 * the PQauthDataHook, or by a message on standard error if no hook is set.
2607 */
2608static bool
2610{
2611 int res;
2612 PGpromptOAuthDevice prompt = {
2614 .user_code = actx->authz.user_code,
2615 .verification_uri_complete = actx->authz.verification_uri_complete,
2616 .expires_in = actx->authz.expires_in,
2617 };
2619
2620 res = hook(PQAUTHDATA_PROMPT_OAUTH_DEVICE, conn, &prompt);
2621
2622 if (!res)
2623 {
2624 /*
2625 * translator: The first %s is a URL for the user to visit in a
2626 * browser, and the second %s is a code to be copy-pasted there.
2627 */
2628 fprintf(stderr, libpq_gettext("Visit %s and enter the code: %s\n"),
2629 prompt.verification_uri, prompt.user_code);
2630 }
2631 else if (res < 0)
2632 {
2633 actx_error(actx, "device prompt failed");
2634 return false;
2635 }
2636
2637 return true;
2638}
2639
2640/*
2641 * Calls curl_global_init() in a thread-safe way.
2642 *
2643 * libcurl has stringent requirements for the thread context in which you call
2644 * curl_global_init(), because it's going to try initializing a bunch of other
2645 * libraries (OpenSSL, Winsock, etc). Recent versions of libcurl have improved
2646 * the thread-safety situation, but there's a chicken-and-egg problem at
2647 * runtime: you can't check the thread safety until you've initialized libcurl,
2648 * which you can't do from within a thread unless you know it's thread-safe...
2649 *
2650 * Returns true if initialization was successful. Successful or not, this
2651 * function will not try to reinitialize Curl on successive calls.
2652 */
2653static bool
2655{
2656 /*
2657 * Don't let the compiler play tricks with this variable. In the
2658 * HAVE_THREADSAFE_CURL_GLOBAL_INIT case, we don't care if two threads
2659 * enter simultaneously, but we do care if this gets set transiently to
2660 * PG_BOOL_YES/NO in cases where that's not the final answer.
2661 */
2662 static volatile PGTernaryBool init_successful = PG_BOOL_UNKNOWN;
2663#if HAVE_THREADSAFE_CURL_GLOBAL_INIT
2664 curl_version_info_data *info;
2665#endif
2666
2667#if !HAVE_THREADSAFE_CURL_GLOBAL_INIT
2668
2669 /*
2670 * Lock around the whole function. If a libpq client performs its own work
2671 * with libcurl, it must either ensure that Curl is initialized safely
2672 * before calling us (in which case our call will be a no-op), or else it
2673 * must guard its own calls to curl_global_init() with a registered
2674 * threadlock handler. See PQregisterThreadLock().
2675 */
2676 pglock_thread();
2677#endif
2678
2679 /*
2680 * Skip initialization if we've already done it. (Curl tracks the number
2681 * of calls; there's no point in incrementing the counter every time we
2682 * connect.)
2683 */
2684 if (init_successful == PG_BOOL_YES)
2685 goto done;
2686 else if (init_successful == PG_BOOL_NO)
2687 {
2689 "curl_global_init previously failed during OAuth setup");
2690 goto done;
2691 }
2692
2693 /*
2694 * We know we've already initialized Winsock by this point (see
2695 * pqMakeEmptyPGconn()), so we should be able to safely skip that bit. But
2696 * we have to tell libcurl to initialize everything else, because other
2697 * pieces of our client executable may already be using libcurl for their
2698 * own purposes. If we initialize libcurl with only a subset of its
2699 * features, we could break those other clients nondeterministically, and
2700 * that would probably be a nightmare to debug.
2701 *
2702 * If some other part of the program has already called this, it's a
2703 * no-op.
2704 */
2705 if (curl_global_init(CURL_GLOBAL_ALL & ~CURL_GLOBAL_WIN32) != CURLE_OK)
2706 {
2708 "curl_global_init failed during OAuth setup");
2709 init_successful = PG_BOOL_NO;
2710 goto done;
2711 }
2712
2713#if HAVE_THREADSAFE_CURL_GLOBAL_INIT
2714
2715 /*
2716 * If we determined at configure time that the Curl installation is
2717 * thread-safe, our job here is much easier. We simply initialize above
2718 * without any locking (concurrent or duplicated calls are fine in that
2719 * situation), then double-check to make sure the runtime setting agrees,
2720 * to try to catch silent downgrades.
2721 */
2722 info = curl_version_info(CURLVERSION_NOW);
2723 if (!(info->features & CURL_VERSION_THREADSAFE))
2724 {
2725 /*
2726 * In a downgrade situation, the damage is already done. Curl global
2727 * state may be corrupted. Be noisy.
2728 */
2729 libpq_append_conn_error(conn, "libcurl is no longer thread-safe\n"
2730 "\tCurl initialization was reported thread-safe when libpq\n"
2731 "\twas compiled, but the currently installed version of\n"
2732 "\tlibcurl reports that it is not. Recompile libpq against\n"
2733 "\tthe installed version of libcurl.");
2734 init_successful = PG_BOOL_NO;
2735 goto done;
2736 }
2737#endif
2738
2739 init_successful = PG_BOOL_YES;
2740
2741done:
2742#if !HAVE_THREADSAFE_CURL_GLOBAL_INIT
2744#endif
2745 return (init_successful == PG_BOOL_YES);
2746}
2747
2748/*
2749 * The core nonblocking libcurl implementation. This will be called several
2750 * times to pump the async engine.
2751 *
2752 * The architecture is based on PQconnectPoll(). The first half drives the
2753 * connection state forward as necessary, returning if we're not ready to
2754 * proceed to the next step yet. The second half performs the actual transition
2755 * between states.
2756 *
2757 * You can trace the overall OAuth flow through the second half. It's linear
2758 * until we get to the end, where we flip back and forth between
2759 * OAUTH_STEP_TOKEN_REQUEST and OAUTH_STEP_WAIT_INTERVAL to regularly ping the
2760 * provider.
2761 */
2764{
2766 struct async_ctx *actx;
2767 char *oauth_token = NULL;
2769
2770 if (!initialize_curl(conn))
2771 return PGRES_POLLING_FAILED;
2772
2773 if (!state->async_ctx)
2774 {
2775 /*
2776 * Create our asynchronous state, and hook it into the upper-level
2777 * OAuth state immediately, so any failures below won't leak the
2778 * context allocation.
2779 */
2780 actx = calloc(1, sizeof(*actx));
2781 if (!actx)
2782 {
2783 libpq_append_conn_error(conn, "out of memory");
2784 return PGRES_POLLING_FAILED;
2785 }
2786
2787 actx->mux = PGINVALID_SOCKET;
2788 actx->timerfd = -1;
2789
2790 /* Should we enable unsafe features? */
2792
2793 state->async_ctx = actx;
2794
2795 initPQExpBuffer(&actx->work_data);
2796 initPQExpBuffer(&actx->errbuf);
2797
2798 if (!setup_multiplexer(actx))
2799 goto error_return;
2800
2801 if (!setup_curl_handles(actx))
2802 goto error_return;
2803 }
2804
2805 actx = state->async_ctx;
2806
2807 do
2808 {
2809 /* By default, the multiplexer is the altsock. Reassign as desired. */
2810 set_conn_altsock(conn, actx->mux);
2811
2812 switch (actx->step)
2813 {
2814 case OAUTH_STEP_INIT:
2815 break;
2816
2820 {
2822
2823 /*
2824 * Clear any expired timeout before calling back into
2825 * Curl. Curl is not guaranteed to do this for us, because
2826 * its API expects us to use single-shot (i.e.
2827 * edge-triggered) timeouts, and ours are level-triggered
2828 * via the mux.
2829 *
2830 * This can't be combined with the comb_multiplexer() call
2831 * below: we might accidentally clear a short timeout that
2832 * was both set and expired during the call to
2833 * drive_request().
2834 */
2835 if (!drain_timer_events(actx, NULL))
2836 goto error_return;
2837
2838 /* Move the request forward. */
2839 status = drive_request(actx);
2840
2841 if (status == PGRES_POLLING_FAILED)
2842 goto error_return;
2843 else if (status == PGRES_POLLING_OK)
2844 break; /* done! */
2845
2846 /*
2847 * This request is still running.
2848 *
2849 * Make sure that stale events don't cause us to come back
2850 * early. (Currently, this can occur only with kqueue.) If
2851 * this is forgotten, the multiplexer can get stuck in a
2852 * signaled state and we'll burn CPU cycles pointlessly.
2853 */
2854 if (!comb_multiplexer(actx))
2855 goto error_return;
2856
2857 return status;
2858 }
2859
2861 {
2862 bool expired;
2863
2864 /*
2865 * The client application is supposed to wait until our
2866 * timer expires before calling PQconnectPoll() again, but
2867 * that might not happen. To avoid sending a token request
2868 * early, check the timer before continuing.
2869 */
2870 if (!drain_timer_events(actx, &expired))
2871 goto error_return;
2872
2873 if (!expired)
2874 {
2876 return PGRES_POLLING_READING;
2877 }
2878
2879 break;
2880 }
2881 }
2882
2883 /*
2884 * Each case here must ensure that actx->running is set while we're
2885 * waiting on some asynchronous work. Most cases rely on
2886 * start_request() to do that for them.
2887 */
2888 switch (actx->step)
2889 {
2890 case OAUTH_STEP_INIT:
2891 actx->errctx = "failed to fetch OpenID discovery document";
2893 goto error_return;
2894
2895 actx->step = OAUTH_STEP_DISCOVERY;
2896 break;
2897
2899 if (!finish_discovery(actx))
2900 goto error_return;
2901
2902 if (!check_issuer(actx, conn))
2903 goto error_return;
2904
2905 actx->errctx = "cannot run OAuth device authorization";
2906 if (!check_for_device_flow(actx))
2907 goto error_return;
2908
2909 actx->errctx = "failed to obtain device authorization";
2910 if (!start_device_authz(actx, conn))
2911 goto error_return;
2912
2914 break;
2915
2917 if (!finish_device_authz(actx))
2918 goto error_return;
2919
2920 actx->errctx = "failed to obtain access token";
2921 if (!start_token_request(actx, conn))
2922 goto error_return;
2923
2925 break;
2926
2928 if (!handle_token_response(actx, &oauth_token))
2929 goto error_return;
2930
2931 /*
2932 * Hook any oauth_token into the PGconn immediately so that
2933 * the allocation isn't lost in case of an error.
2934 */
2935 set_conn_oauth_token(conn, oauth_token);
2936
2937 if (!actx->user_prompted)
2938 {
2939 /*
2940 * Now that we know the token endpoint isn't broken, give
2941 * the user the login instructions.
2942 */
2943 if (!prompt_user(actx, conn))
2944 goto error_return;
2945
2946 actx->user_prompted = true;
2947 }
2948
2949 if (oauth_token)
2950 break; /* done! */
2951
2952 /*
2953 * Wait for the required interval before issuing the next
2954 * request.
2955 */
2956 if (!set_timer(actx, actx->authz.interval * 1000))
2957 goto error_return;
2958
2959 /*
2960 * No Curl requests are running, so we can simplify by having
2961 * the client wait directly on the timerfd rather than the
2962 * multiplexer.
2963 */
2965
2967 actx->running = 1;
2968 break;
2969
2971 actx->errctx = "failed to obtain access token";
2972 if (!start_token_request(actx, conn))
2973 goto error_return;
2974
2976 break;
2977 }
2978
2979 /*
2980 * The vast majority of the time, if we don't have a token at this
2981 * point, actx->running will be set. But there are some corner cases
2982 * where we can immediately loop back around; see start_request().
2983 */
2984 } while (!oauth_token && !actx->running);
2985
2986 /* If we've stored a token, we're done. Otherwise come back later. */
2987 return oauth_token ? PGRES_POLLING_OK : PGRES_POLLING_READING;
2988
2989error_return:
2991
2992 /*
2993 * Assemble the three parts of our error: context, body, and detail. See
2994 * also the documentation for struct async_ctx.
2995 */
2996 if (actx->errctx)
2998
2999 if (PQExpBufferDataBroken(actx->errbuf))
3000 appendPQExpBufferStr(errbuf, libpq_gettext("out of memory"));
3001 else
3003
3004 if (actx->curl_err[0])
3005 {
3006 appendPQExpBuffer(errbuf, " (libcurl: %s)", actx->curl_err);
3007
3008 /* Sometimes libcurl adds a newline to the error buffer. :( */
3009 if (errbuf->len >= 2 && errbuf->data[errbuf->len - 2] == '\n')
3010 {
3011 errbuf->data[errbuf->len - 2] = ')';
3012 errbuf->data[errbuf->len - 1] = '\0';
3013 errbuf->len--;
3014 }
3015 }
3016
3018
3019 return PGRES_POLLING_FAILED;
3020}
3021
3022/*
3023 * The top-level entry point. This is a convenient place to put necessary
3024 * wrapper logic before handing off to the true implementation, above.
3025 */
3028{
3031 struct async_ctx *actx;
3032#ifndef WIN32
3033 sigset_t osigset;
3034 bool sigpipe_pending;
3035 bool masked;
3036
3037 /*---
3038 * Ignore SIGPIPE on this thread during all Curl processing.
3039 *
3040 * Because we support multiple threads, we have to set up libcurl with
3041 * CURLOPT_NOSIGNAL, which disables its default global handling of
3042 * SIGPIPE. From the Curl docs:
3043 *
3044 * libcurl makes an effort to never cause such SIGPIPE signals to
3045 * trigger, but some operating systems have no way to avoid them and
3046 * even on those that have there are some corner cases when they may
3047 * still happen, contrary to our desire.
3048 *
3049 * Note that libcurl is also at the mercy of its DNS resolution and SSL
3050 * libraries; if any of them forget a MSG_NOSIGNAL then we're in trouble.
3051 * Modern platforms and libraries seem to get it right, so this is a
3052 * difficult corner case to exercise in practice, and unfortunately it's
3053 * not really clear whether it's necessary in all cases.
3054 */
3055 masked = (pq_block_sigpipe(&osigset, &sigpipe_pending) == 0);
3056#endif
3057
3059
3060 /*
3061 * To assist with finding bugs in comb_multiplexer() and
3062 * drain_timer_events(), when we're in debug mode, track the total number
3063 * of calls to this function and print that at the end of the flow.
3064 *
3065 * Be careful that state->async_ctx could be NULL if early initialization
3066 * fails during the first call.
3067 */
3068 actx = state->async_ctx;
3069 Assert(actx || result == PGRES_POLLING_FAILED);
3070
3071 if (actx && actx->debugging)
3072 {
3073 actx->dbg_num_calls++;
3074 if (result == PGRES_POLLING_OK || result == PGRES_POLLING_FAILED)
3075 fprintf(stderr, "[libpq] total number of polls: %d\n",
3076 actx->dbg_num_calls);
3077 }
3078
3079#ifndef WIN32
3080 if (masked)
3081 {
3082 /*
3083 * Undo the SIGPIPE mask. Assume we may have gotten EPIPE (we have no
3084 * way of knowing at this level).
3085 */
3086 pq_reset_sigpipe(&osigset, sigpipe_pending, true /* EPIPE, maybe */ );
3087 }
3088#endif
3089
3090 return result;
3091}
static void cleanup(void)
Definition: bootstrap.c:715
#define lengthof(array)
Definition: c.h:792
#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 @171 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:3027
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:2075
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:2501
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:2032
static bool start_token_request(struct async_ctx *actx, PGconn *conn)
Definition: oauth-curl.c:2469
static bool initialize_curl(PGconn *conn)
Definition: oauth-curl.c:2654
#define HTTPS_SCHEME
Definition: oauth-curl.c:2229
#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:2297
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:2090
#define PG_CURL_IGNORE_DEPRECATION(x)
Definition: oauth-curl.c:1926
#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:1933
static bool start_device_authz(struct async_ctx *actx, PGconn *conn)
Definition: oauth-curl.c:2381
static bool prompt_user(struct async_ctx *actx, PGconn *conn)
Definition: oauth-curl.c:2609
#define CHECK_MSETOPT(ACTX, OPT, VAL, FAILACTION)
Definition: oauth-curl.c:385
static bool finish_discovery(struct async_ctx *actx)
Definition: oauth-curl.c:2128
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:2119
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:2412
#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:2763
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:2230
#define conn_oauth_client_id(CONN)
Definition: oauth-curl.c:54
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:2193
#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:2548
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:2238
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
union json_field::@194 target
JsonTokenType type
Definition: oauth-curl.c:435
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