Age Owner Branch data TLA Line data Source code
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 : : */
114 : : struct provider
115 : : {
116 : : char *issuer;
117 : : char *token_endpoint;
118 : : char *device_authorization_endpoint;
119 : : struct curl_slist *grant_types_supported;
120 : : };
121 : :
122 : : static void
198 dgustafsson@postgres 123 :CBC 48 : free_provider(struct provider *provider)
124 : : {
125 : 48 : free(provider->issuer);
126 : 48 : free(provider->token_endpoint);
127 : 48 : free(provider->device_authorization_endpoint);
128 : 48 : curl_slist_free_all(provider->grant_types_supported);
129 : 48 : }
130 : :
131 : : /*
132 : : * The Device Authorization response, described by RFC 8628:
133 : : *
134 : : * https://www.rfc-editor.org/rfc/rfc8628#section-3.2
135 : : */
136 : : struct device_authz
137 : : {
138 : : char *device_code;
139 : : char *user_code;
140 : : char *verification_uri;
141 : : char *verification_uri_complete;
142 : : char *expires_in_str;
143 : : char *interval_str;
144 : :
145 : : /* Fields below are parsed from the corresponding string above. */
146 : : int expires_in;
147 : : int interval;
148 : : };
149 : :
150 : : static void
151 : 48 : free_device_authz(struct device_authz *authz)
152 : : {
153 : 48 : free(authz->device_code);
154 : 48 : free(authz->user_code);
155 : 48 : free(authz->verification_uri);
156 : 48 : free(authz->verification_uri_complete);
157 : 48 : free(authz->expires_in_str);
158 : 48 : free(authz->interval_str);
159 : 48 : }
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 : : */
169 : : struct token_error
170 : : {
171 : : char *error;
172 : : char *error_description;
173 : : };
174 : :
175 : : static void
176 : 51 : free_token_error(struct token_error *err)
177 : : {
178 : 51 : free(err->error);
179 : 51 : free(err->error_description);
180 : 51 : }
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 : : */
191 : : struct token
192 : : {
193 : : /* for successful responses */
194 : : char *access_token;
195 : : char *token_type;
196 : :
197 : : /* for error responses */
198 : : struct token_error err;
199 : : };
200 : :
201 : : static void
202 : 51 : free_token(struct token *tok)
203 : : {
204 : 51 : free(tok->access_token);
205 : 51 : free(tok->token_type);
206 : 51 : free_token_error(&tok->err);
207 : 51 : }
208 : :
209 : : /*
210 : : * Asynchronous State
211 : : */
212 : :
213 : : /* States for the overall async machine. */
214 : : enum OAuthStep
215 : : {
216 : : OAUTH_STEP_INIT = 0,
217 : : OAUTH_STEP_DISCOVERY,
218 : : OAUTH_STEP_DEVICE_AUTHORIZATION,
219 : : OAUTH_STEP_TOKEN_REQUEST,
220 : : OAUTH_STEP_WAIT_INTERVAL,
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 : : */
228 : : struct async_ctx
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 */
267 : : PQExpBufferData errbuf;
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 : : */
274 : : struct provider provider;
275 : : struct device_authz authz;
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 : : */
287 : : static void
288 : 48 : free_async_ctx(PGconn *conn, struct async_ctx *actx)
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 [ + - + - ]: 48 : if (actx->curlm && actx->curl)
302 : : {
303 : 48 : CURLMcode err = curl_multi_remove_handle(actx->curlm, actx->curl);
304 : :
305 [ - + ]: 48 : if (err)
198 dgustafsson@postgres 306 :UBC 0 : libpq_append_conn_error(conn,
307 : : "libcurl easy handle removal failed: %s",
308 : : curl_multi_strerror(err));
309 : : }
310 : :
198 dgustafsson@postgres 311 [ + - ]:CBC 48 : 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 : 48 : curl_easy_cleanup(actx->curl);
319 : : }
320 : :
321 [ + - ]: 48 : if (actx->curlm)
322 : : {
323 : 48 : CURLMcode err = curl_multi_cleanup(actx->curlm);
324 : :
325 [ - + ]: 48 : if (err)
198 dgustafsson@postgres 326 :UBC 0 : libpq_append_conn_error(conn,
327 : : "libcurl multi handle cleanup failed: %s",
328 : : curl_multi_strerror(err));
329 : : }
330 : :
198 dgustafsson@postgres 331 :CBC 48 : free_provider(&actx->provider);
332 : 48 : free_device_authz(&actx->authz);
333 : :
334 : 48 : curl_slist_free_all(actx->headers);
335 : 48 : termPQExpBuffer(&actx->work_data);
336 : 48 : termPQExpBuffer(&actx->errbuf);
337 : :
338 [ + - ]: 48 : if (actx->mux != PGINVALID_SOCKET)
339 : 48 : close(actx->mux);
340 [ + - ]: 48 : if (actx->timerfd >= 0)
341 : 48 : close(actx->timerfd);
342 : :
343 : 48 : free(actx);
344 : 48 : }
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 : : */
354 : : void
355 : 49 : pg_fe_cleanup_oauth_flow(PGconn *conn)
356 : : {
128 jchampion@postgresql 357 : 49 : fe_oauth_state *state = conn_sasl_state(conn);
358 : :
198 dgustafsson@postgres 359 [ + + ]: 49 : if (state->async_ctx)
360 : : {
361 : 48 : free_async_ctx(conn, state->async_ctx);
362 : 48 : state->async_ctx = NULL;
363 : : }
364 : :
128 jchampion@postgresql 365 : 49 : set_conn_altsock(conn, PGINVALID_SOCKET);
198 dgustafsson@postgres 366 : 49 : }
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 : : */
431 : : struct json_field
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 */
442 : : } target;
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(). */
452 : : struct oauth_parse
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 : :
464 : : static void
198 dgustafsson@postgres 465 :UBC 0 : report_type_mismatch(struct oauth_parse *ctx)
466 : : {
467 : : char *msgfmt;
468 : :
469 [ # # ]: 0 : 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 [ # # # # ]: 0 : switch (ctx->active->type)
476 : : {
477 : 0 : case JSON_TOKEN_STRING:
478 : 0 : msgfmt = "field \"%s\" must be a string";
479 : 0 : break;
480 : :
481 : 0 : case JSON_TOKEN_NUMBER:
482 : 0 : msgfmt = "field \"%s\" must be a number";
483 : 0 : break;
484 : :
485 : 0 : case JSON_TOKEN_ARRAY_START:
486 : 0 : msgfmt = "field \"%s\" must be an array of strings";
487 : 0 : break;
488 : :
489 : 0 : default:
490 : 0 : Assert(false);
491 : : msgfmt = "field \"%s\" has unexpected type";
492 : : }
493 : :
494 : 0 : oauth_parse_set_error(ctx, msgfmt, ctx->active->name);
495 : 0 : }
496 : :
497 : : static JsonParseErrorType
198 dgustafsson@postgres 498 :CBC 174 : oauth_json_object_start(void *state)
499 : : {
500 : 174 : struct oauth_parse *ctx = state;
501 : :
502 [ - + ]: 174 : 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 : : */
198 dgustafsson@postgres 508 :UBC 0 : report_type_mismatch(ctx);
509 : 0 : return JSON_SEM_ACTION_FAILED;
510 : : }
511 : :
198 dgustafsson@postgres 512 :CBC 174 : ++ctx->nested;
106 jchampion@postgresql 513 [ + + ]: 174 : if (ctx->nested > MAX_OAUTH_NESTING_LEVEL)
514 : : {
515 : 1 : oauth_parse_set_error(ctx, "JSON is too deeply nested");
516 : 1 : return JSON_SEM_ACTION_FAILED;
517 : : }
518 : :
198 dgustafsson@postgres 519 : 173 : return JSON_SUCCESS;
520 : : }
521 : :
522 : : static JsonParseErrorType
523 : 683 : oauth_json_object_field_start(void *state, char *name, bool isnull)
524 : : {
525 : 683 : struct oauth_parse *ctx = state;
526 : :
527 : : /* We care only about the top-level fields. */
528 [ + + ]: 683 : if (ctx->nested == 1)
529 : : {
530 : 653 : 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 [ - + ]: 653 : if (ctx->active)
537 : : {
198 dgustafsson@postgres 538 :UBC 0 : Assert(false);
539 : : oauth_parse_set_error(ctx,
540 : : "internal error: started field '%s' before field '%s' was finished",
541 : : name, ctx->active->name);
542 : : return JSON_SEM_ACTION_FAILED;
543 : : }
544 : :
198 dgustafsson@postgres 545 [ + + ]:CBC 2118 : while (field->name)
546 : : {
547 [ + + ]: 1970 : if (strcmp(name, field->name) == 0)
548 : : {
549 : 505 : ctx->active = field;
550 : 505 : break;
551 : : }
552 : :
553 : 1465 : ++field;
554 : : }
555 : :
556 : : /*
557 : : * We don't allow duplicate field names; error out if the target has
558 : : * already been set.
559 : : */
560 [ + + ]: 653 : if (ctx->active)
561 : : {
562 : 505 : field = ctx->active;
563 : :
564 [ + + + - ]: 505 : if ((field->type == JSON_TOKEN_ARRAY_START && *field->target.array)
565 [ + + - + ]: 505 : || (field->type != JSON_TOKEN_ARRAY_START && *field->target.scalar))
566 : : {
198 dgustafsson@postgres 567 :UBC 0 : oauth_parse_set_error(ctx, "field \"%s\" is duplicated",
568 : : field->name);
569 : 0 : return JSON_SEM_ACTION_FAILED;
570 : : }
571 : : }
572 : : }
573 : :
198 dgustafsson@postgres 574 :CBC 683 : return JSON_SUCCESS;
575 : : }
576 : :
577 : : static JsonParseErrorType
578 : 156 : oauth_json_object_end(void *state)
579 : : {
580 : 156 : struct oauth_parse *ctx = state;
581 : :
582 : 156 : --ctx->nested;
583 : :
584 : : /*
585 : : * All fields should be fully processed by the end of the top-level
586 : : * object.
587 : : */
588 [ + + - + ]: 156 : if (!ctx->nested && ctx->active)
589 : : {
198 dgustafsson@postgres 590 :UBC 0 : Assert(false);
591 : : oauth_parse_set_error(ctx,
592 : : "internal error: field '%s' still active at end of object",
593 : : ctx->active->name);
594 : : return JSON_SEM_ACTION_FAILED;
595 : : }
596 : :
198 dgustafsson@postgres 597 :CBC 156 : return JSON_SUCCESS;
598 : : }
599 : :
600 : : static JsonParseErrorType
601 : 223 : oauth_json_array_start(void *state)
602 : : {
603 : 223 : struct oauth_parse *ctx = state;
604 : :
605 [ - + ]: 223 : if (!ctx->nested)
606 : : {
198 dgustafsson@postgres 607 :UBC 0 : oauth_parse_set_error(ctx, "top-level element must be an object");
608 : 0 : return JSON_SEM_ACTION_FAILED;
609 : : }
610 : :
198 dgustafsson@postgres 611 [ + + ]:CBC 223 : if (ctx->active)
612 : : {
613 [ + - ]: 48 : if (ctx->active->type != JSON_TOKEN_ARRAY_START
614 : : /* The arrays we care about must not have arrays as values. */
615 [ - + ]: 48 : || ctx->nested > 1)
616 : : {
198 dgustafsson@postgres 617 :UBC 0 : report_type_mismatch(ctx);
618 : 0 : return JSON_SEM_ACTION_FAILED;
619 : : }
620 : : }
621 : :
198 dgustafsson@postgres 622 :CBC 223 : ++ctx->nested;
106 jchampion@postgresql 623 [ + + ]: 223 : if (ctx->nested > MAX_OAUTH_NESTING_LEVEL)
624 : : {
625 : 1 : oauth_parse_set_error(ctx, "JSON is too deeply nested");
626 : 1 : return JSON_SEM_ACTION_FAILED;
627 : : }
628 : :
198 dgustafsson@postgres 629 : 222 : return JSON_SUCCESS;
630 : : }
631 : :
632 : : static JsonParseErrorType
633 : 207 : oauth_json_array_end(void *state)
634 : : {
635 : 207 : struct oauth_parse *ctx = state;
636 : :
637 [ + + ]: 207 : 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 [ + - - + ]: 48 : if (ctx->nested != 2 || ctx->active->type != JSON_TOKEN_ARRAY_START)
645 : : {
198 dgustafsson@postgres 646 :UBC 0 : Assert(false);
647 : : oauth_parse_set_error(ctx,
648 : : "internal error: found unexpected array end while parsing field '%s'",
649 : : ctx->active->name);
650 : : return JSON_SEM_ACTION_FAILED;
651 : : }
652 : :
198 dgustafsson@postgres 653 :CBC 48 : ctx->active = NULL;
654 : : }
655 : :
656 : 207 : --ctx->nested;
657 : 207 : return JSON_SUCCESS;
658 : : }
659 : :
660 : : static JsonParseErrorType
661 : 699 : oauth_json_scalar(void *state, char *token, JsonTokenType type)
662 : : {
663 : 699 : struct oauth_parse *ctx = state;
664 : :
665 [ - + ]: 699 : if (!ctx->nested)
666 : : {
198 dgustafsson@postgres 667 :UBC 0 : oauth_parse_set_error(ctx, "top-level element must be an object");
668 : 0 : return JSON_SEM_ACTION_FAILED;
669 : : }
670 : :
198 dgustafsson@postgres 671 [ + + ]:CBC 699 : if (ctx->active)
672 : : {
673 : 553 : const struct json_field *field = ctx->active;
674 : 553 : JsonTokenType expected = field->type;
675 : :
676 : : /* Make sure this matches what the active field expects. */
677 [ + + ]: 553 : if (expected == JSON_TOKEN_ARRAY_START)
678 : : {
679 : : /* Are we actually inside an array? */
680 [ - + ]: 96 : if (ctx->nested < 2)
681 : : {
198 dgustafsson@postgres 682 :UBC 0 : report_type_mismatch(ctx);
683 : 0 : return JSON_SEM_ACTION_FAILED;
684 : : }
685 : :
686 : : /* Currently, arrays can only contain strings. */
198 dgustafsson@postgres 687 :CBC 96 : expected = JSON_TOKEN_STRING;
688 : : }
689 : :
690 [ - + ]: 553 : if (type != expected)
691 : : {
198 dgustafsson@postgres 692 :UBC 0 : report_type_mismatch(ctx);
693 : 0 : return JSON_SEM_ACTION_FAILED;
694 : : }
695 : :
198 dgustafsson@postgres 696 [ + + ]:CBC 553 : if (field->type != JSON_TOKEN_ARRAY_START)
697 : : {
698 : : /* Ensure that we're parsing the top-level keys... */
699 [ - + ]: 457 : if (ctx->nested != 1)
700 : : {
198 dgustafsson@postgres 701 :UBC 0 : Assert(false);
702 : : oauth_parse_set_error(ctx,
703 : : "internal error: scalar target found at nesting level %d",
704 : : ctx->nested);
705 : : return JSON_SEM_ACTION_FAILED;
706 : : }
707 : :
708 : : /* ...and that a result has not already been set. */
198 dgustafsson@postgres 709 [ - + ]:CBC 457 : if (*field->target.scalar)
710 : : {
198 dgustafsson@postgres 711 :UBC 0 : Assert(false);
712 : : oauth_parse_set_error(ctx,
713 : : "internal error: scalar field '%s' would be assigned twice",
714 : : ctx->active->name);
715 : : return JSON_SEM_ACTION_FAILED;
716 : : }
717 : :
198 dgustafsson@postgres 718 :CBC 457 : *field->target.scalar = strdup(token);
719 [ - + ]: 457 : if (!*field->target.scalar)
198 dgustafsson@postgres 720 :UBC 0 : return JSON_OUT_OF_MEMORY;
721 : :
198 dgustafsson@postgres 722 :CBC 457 : ctx->active = NULL;
723 : :
724 : 457 : 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 [ - + ]: 96 : if (ctx->nested != 2)
732 : : {
198 dgustafsson@postgres 733 :UBC 0 : Assert(false);
734 : : oauth_parse_set_error(ctx,
735 : : "internal error: array member found at nesting level %d",
736 : : ctx->nested);
737 : : return JSON_SEM_ACTION_FAILED;
738 : : }
739 : :
740 : : /* Note that curl_slist_append() makes a copy of the token. */
198 dgustafsson@postgres 741 :CBC 96 : temp = curl_slist_append(*field->target.array, token);
742 [ - + ]: 96 : if (!temp)
198 dgustafsson@postgres 743 :UBC 0 : return JSON_OUT_OF_MEMORY;
744 : :
198 dgustafsson@postgres 745 :CBC 96 : *field->target.array = temp;
746 : : }
747 : : }
748 : : else
749 : : {
750 : : /* otherwise we just ignore it */
751 : : }
752 : :
753 : 242 : return JSON_SUCCESS;
754 : : }
755 : :
756 : : /*
757 : : * Checks the Content-Type header against the expected type. Parameters are
758 : : * allowed but ignored.
759 : : */
760 : : static bool
761 : 146 : check_content_type(struct async_ctx *actx, const char *type)
762 : : {
763 : 146 : const size_t type_len = strlen(type);
764 : : char *content_type;
765 : :
766 [ - + ]: 146 : CHECK_GETINFO(actx, CURLINFO_CONTENT_TYPE, &content_type, return false);
767 : :
768 [ - + ]: 146 : if (!content_type)
769 : : {
198 dgustafsson@postgres 770 :UBC 0 : actx_error(actx, "no content type was provided");
771 : 0 : return false;
772 : : }
773 : :
774 : : /*
775 : : * We need to perform a length limited comparison and not compare the
776 : : * whole string.
777 : : */
198 dgustafsson@postgres 778 [ + + ]:CBC 146 : if (pg_strncasecmp(content_type, type, type_len) != 0)
779 : 2 : goto fail;
780 : :
781 : : /* On an exact match, we're done. */
782 [ - + ]: 144 : Assert(strlen(content_type) >= type_len);
783 [ + + ]: 144 : if (content_type[type_len] == '\0')
784 : 139 : 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 [ + - ]: 9 : for (size_t i = type_len; content_type[i]; ++i)
792 : : {
793 [ + + + ]: 9 : switch (content_type[i])
794 : : {
795 : 4 : case ';':
796 : 4 : return true; /* success! */
797 : :
798 : 4 : case ' ':
799 : : case '\t':
800 : : /* HTTP optional whitespace allows only spaces and htabs. */
801 : 4 : break;
802 : :
803 : 1 : default:
804 : 1 : goto fail;
805 : : }
806 : : }
807 : :
198 dgustafsson@postgres 808 :UBC 0 : fail:
198 dgustafsson@postgres 809 :CBC 3 : actx_error(actx, "unexpected content type: \"%s\"", content_type);
810 : 3 : 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 : : */
819 : : static bool
820 : 146 : parse_oauth_json(struct async_ctx *actx, const struct json_field *fields)
821 : : {
822 : 146 : PQExpBuffer resp = &actx->work_data;
823 : 146 : JsonLexContext lex = {0};
824 : 146 : JsonSemAction sem = {0};
825 : : JsonParseErrorType err;
826 : 146 : struct oauth_parse ctx = {0};
827 : 146 : bool success = false;
828 : :
829 [ + + ]: 146 : if (!check_content_type(actx, "application/json"))
830 : 3 : return false;
831 : :
832 [ - + ]: 143 : if (strlen(resp->data) != resp->len)
833 : : {
198 dgustafsson@postgres 834 :UBC 0 : actx_error(actx, "response contains embedded NULLs");
835 : 0 : 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 : : */
198 dgustafsson@postgres 842 [ - + ]:CBC 143 : if (pg_encoding_verifymbstr(PG_UTF8, resp->data, resp->len) != resp->len)
843 : : {
198 dgustafsson@postgres 844 :UBC 0 : actx_error(actx, "response is not valid UTF-8");
845 : 0 : return false;
846 : : }
847 : :
198 dgustafsson@postgres 848 :CBC 143 : makeJsonLexContextCstringLen(&lex, resp->data, resp->len, PG_UTF8, true);
849 : 143 : setJsonLexContextOwnsTokens(&lex, true); /* must not leak on error */
850 : :
851 : 143 : ctx.errbuf = &actx->errbuf;
852 : 143 : ctx.fields = fields;
853 : 143 : sem.semstate = &ctx;
854 : :
855 : 143 : sem.object_start = oauth_json_object_start;
856 : 143 : sem.object_field_start = oauth_json_object_field_start;
857 : 143 : sem.object_end = oauth_json_object_end;
858 : 143 : sem.array_start = oauth_json_array_start;
859 : 143 : sem.array_end = oauth_json_array_end;
860 : 143 : sem.scalar = oauth_json_scalar;
861 : :
862 : 143 : err = pg_parse_json(&lex, &sem);
863 : :
864 [ + + ]: 143 : 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 : : */
871 [ - + ]: 2 : if (err != JSON_SEM_ACTION_FAILED)
198 dgustafsson@postgres 872 :UBC 0 : actx_error_str(actx, json_errdetail(err, &lex));
873 : :
198 dgustafsson@postgres 874 :CBC 2 : goto cleanup;
875 : : }
876 : :
877 : : /* Check all required fields. */
878 [ + + ]: 739 : while (fields->name)
879 : : {
880 [ + + ]: 598 : if (fields->required
881 [ - + ]: 399 : && !*fields->target.scalar
198 dgustafsson@postgres 882 [ # # ]:UBC 0 : && !*fields->target.array)
883 : : {
884 : 0 : actx_error(actx, "field \"%s\" is missing", fields->name);
885 : 0 : goto cleanup;
886 : : }
887 : :
198 dgustafsson@postgres 888 :CBC 598 : fields++;
889 : : }
890 : :
891 : 141 : success = true;
892 : :
893 : 143 : cleanup:
894 : 143 : freeJsonLexContext(&lex);
895 : 143 : 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 : : */
906 : : static bool
907 : 48 : parse_provider(struct async_ctx *actx, struct provider *provider)
908 : : {
909 : 48 : struct json_field fields[] = {
194 910 : 48 : {"issuer", JSON_TOKEN_STRING, {&provider->issuer}, PG_OAUTH_REQUIRED},
911 : 48 : {"token_endpoint", JSON_TOKEN_STRING, {&provider->token_endpoint}, PG_OAUTH_REQUIRED},
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 : 48 : {"device_authorization_endpoint", JSON_TOKEN_STRING, {&provider->device_authorization_endpoint}, PG_OAUTH_OPTIONAL},
924 : 48 : {"grant_types_supported", JSON_TOKEN_ARRAY_START, {.array = &provider->grant_types_supported}, PG_OAUTH_OPTIONAL},
925 : :
926 : : {0},
927 : : };
928 : :
198 929 : 48 : 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 : : */
937 : : static double
938 : 87 : parse_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 : 87 : cnt = sscanf(s, "%lf", &parsed);
948 : :
949 [ - + ]: 87 : 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 : : */
198 dgustafsson@postgres 955 :UBC 0 : Assert(false);
956 : : return 0;
957 : : }
958 : :
198 dgustafsson@postgres 959 :CBC 87 : 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 : : */
972 : : static int
973 : 43 : parse_interval(struct async_ctx *actx, const char *interval_str)
974 : : {
975 : : double parsed;
976 : :
977 : 43 : parsed = parse_json_number(interval_str);
978 : 43 : parsed = ceil(parsed);
979 : :
980 [ + + ]: 43 : if (parsed < 1)
981 : 40 : return actx->debugging ? 0 : 1;
982 : :
983 [ + + ]: 3 : else if (parsed >= INT_MAX)
984 : 1 : return INT_MAX;
985 : :
986 : 2 : 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 : : */
998 : : static int
999 : 44 : parse_expires_in(struct async_ctx *actx, const char *expires_in_str)
1000 : : {
1001 : : double parsed;
1002 : :
1003 : 44 : parsed = parse_json_number(expires_in_str);
1004 : 44 : parsed = floor(parsed);
1005 : :
1006 [ - + ]: 44 : if (parsed >= INT_MAX)
198 dgustafsson@postgres 1007 :UBC 0 : return INT_MAX;
198 dgustafsson@postgres 1008 [ - + ]:CBC 44 : else if (parsed <= INT_MIN)
198 dgustafsson@postgres 1009 :UBC 0 : return INT_MIN;
1010 : :
198 dgustafsson@postgres 1011 :CBC 44 : return parsed;
1012 : : }
1013 : :
1014 : : /*
1015 : : * Parses the Device Authorization Response (RFC 8628, Sec. 3.2).
1016 : : */
1017 : : static bool
1018 : 47 : parse_device_authz(struct async_ctx *actx, struct device_authz *authz)
1019 : : {
1020 : 47 : struct json_field fields[] = {
194 1021 : 47 : {"device_code", JSON_TOKEN_STRING, {&authz->device_code}, PG_OAUTH_REQUIRED},
1022 : 47 : {"user_code", JSON_TOKEN_STRING, {&authz->user_code}, PG_OAUTH_REQUIRED},
1023 : 47 : {"verification_uri", JSON_TOKEN_STRING, {&authz->verification_uri}, PG_OAUTH_REQUIRED},
1024 : 47 : {"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 : 47 : {"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 : 47 : {"verification_uri_complete", JSON_TOKEN_STRING, {&authz->verification_uri_complete}, PG_OAUTH_OPTIONAL},
1038 : 47 : {"interval", JSON_TOKEN_NUMBER, {&authz->interval_str}, PG_OAUTH_OPTIONAL},
1039 : :
1040 : : {0},
1041 : : };
1042 : :
198 1043 [ + + ]: 47 : if (!parse_oauth_json(actx, fields))
1044 : 3 : 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 [ + + ]: 44 : if (authz->interval_str)
1051 : 43 : 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 : 1 : authz->interval = 5;
1059 : : }
1060 : :
1061 [ - + ]: 44 : Assert(authz->expires_in_str); /* ensured by parse_oauth_json() */
1062 : 44 : authz->expires_in = parse_expires_in(actx, authz->expires_in_str);
1063 : :
1064 : 44 : 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 : : */
1071 : : static bool
1072 : 15 : parse_token_error(struct async_ctx *actx, struct token_error *err)
1073 : : {
1074 : : bool result;
1075 : 15 : struct json_field fields[] = {
194 1076 : 15 : {"error", JSON_TOKEN_STRING, {&err->error}, PG_OAUTH_REQUIRED},
1077 : :
1078 : 15 : {"error_description", JSON_TOKEN_STRING, {&err->error_description}, PG_OAUTH_OPTIONAL},
1079 : :
1080 : : {0},
1081 : : };
1082 : :
198 1083 : 15 : 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 [ - + ]: 15 : if (!result)
198 dgustafsson@postgres 1090 :UBC 0 : actx->errctx = "failed to parse token error response";
1091 : :
198 dgustafsson@postgres 1092 :CBC 15 : return result;
1093 : : }
1094 : :
1095 : : /*
1096 : : * Constructs a message from the token error response and puts it into
1097 : : * actx->errbuf.
1098 : : */
1099 : : static void
1100 : 6 : record_token_error(struct async_ctx *actx, const struct token_error *err)
1101 : : {
1102 [ + + ]: 6 : if (err->error_description)
1103 : 3 : 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 [ - + ]: 3 : CHECK_GETINFO(actx, CURLINFO_RESPONSE_CODE, &response_code, response_code = 0);
1114 : :
1115 [ + + ]: 3 : if (response_code == 401)
1116 : : {
1117 [ + + ]: 2 : 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 : 2 : actx_error_str(actx, " ");
1121 : : }
1122 : : }
1123 : :
1124 : 6 : appendPQExpBuffer(&actx->errbuf, "(%s)", err->error);
1125 : 6 : }
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 : : */
1131 : : static bool
1132 : 36 : parse_access_token(struct async_ctx *actx, struct token *tok)
1133 : : {
1134 : 36 : struct json_field fields[] = {
194 1135 : 36 : {"access_token", JSON_TOKEN_STRING, {&tok->access_token}, PG_OAUTH_REQUIRED},
1136 : 36 : {"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 : :
198 1157 : 36 : 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 : : */
1173 : : static bool
1174 : 50 : setup_multiplexer(struct async_ctx *actx)
1175 : : {
1176 : : #if defined(HAVE_SYS_EPOLL_H)
1177 : 50 : struct epoll_event ev = {.events = EPOLLIN};
1178 : :
1179 : 50 : actx->mux = epoll_create1(EPOLL_CLOEXEC);
1180 [ - + ]: 50 : if (actx->mux < 0)
1181 : : {
198 dgustafsson@postgres 1182 :UBC 0 : actx_error(actx, "failed to create epoll set: %m");
1183 : 0 : return false;
1184 : : }
1185 : :
198 dgustafsson@postgres 1186 :CBC 50 : actx->timerfd = timerfd_create(CLOCK_MONOTONIC, TFD_CLOEXEC);
1187 [ - + ]: 50 : if (actx->timerfd < 0)
1188 : : {
198 dgustafsson@postgres 1189 :UBC 0 : actx_error(actx, "failed to create timerfd: %m");
1190 : 0 : return false;
1191 : : }
1192 : :
198 dgustafsson@postgres 1193 [ - + ]:CBC 50 : if (epoll_ctl(actx->mux, EPOLL_CTL_ADD, actx->timerfd, &ev) < 0)
1194 : : {
198 dgustafsson@postgres 1195 :UBC 0 : actx_error(actx, "failed to add timerfd to epoll set: %m");
1196 : 0 : return false;
1197 : : }
1198 : :
198 dgustafsson@postgres 1199 :CBC 50 : 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 : : */
1232 : : static int
1233 : 449 : register_socket(CURL *curl, curl_socket_t socket, int what, void *ctx,
1234 : : void *socketp)
1235 : : {
1236 : 449 : struct async_ctx *actx = ctx;
1237 : :
1238 : : #if defined(HAVE_SYS_EPOLL_H)
1239 : 449 : struct epoll_event ev = {0};
1240 : : int res;
1241 : 449 : int op = EPOLL_CTL_ADD;
1242 : :
1243 [ + + + + : 449 : switch (what)
- ]
1244 : : {
1245 : 129 : case CURL_POLL_IN:
1246 : 129 : ev.events = EPOLLIN;
1247 : 129 : break;
1248 : :
1249 : 152 : case CURL_POLL_OUT:
1250 : 152 : ev.events = EPOLLOUT;
1251 : 152 : break;
1252 : :
198 dgustafsson@postgres 1253 :GBC 8 : case CURL_POLL_INOUT:
1254 : 8 : ev.events = EPOLLIN | EPOLLOUT;
1255 : 8 : break;
1256 : :
198 dgustafsson@postgres 1257 :CBC 160 : case CURL_POLL_REMOVE:
1258 : 160 : op = EPOLL_CTL_DEL;
1259 : 160 : break;
1260 : :
198 dgustafsson@postgres 1261 :UBC 0 : default:
1262 : 0 : actx_error(actx, "unknown libcurl socket operation: %d", what);
1263 : 0 : return -1;
1264 : : }
1265 : :
198 dgustafsson@postgres 1266 :CBC 449 : res = epoll_ctl(actx->mux, op, socket, &ev);
1267 [ + + + - ]: 449 : if (res < 0 && errno == EEXIST)
1268 : : {
1269 : : /* We already had this socket in the poll set. */
1270 : 129 : op = EPOLL_CTL_MOD;
1271 : 129 : res = epoll_ctl(actx->mux, op, socket, &ev);
1272 : : }
1273 : :
1274 [ - + ]: 449 : if (res < 0)
1275 : : {
198 dgustafsson@postgres 1276 [ # # # ]:UBC 0 : switch (op)
1277 : : {
1278 : 0 : case EPOLL_CTL_ADD:
1279 : 0 : actx_error(actx, "could not add to epoll set: %m");
1280 : 0 : break;
1281 : :
1282 : 0 : case EPOLL_CTL_DEL:
1283 : 0 : actx_error(actx, "could not delete from epoll set: %m");
1284 : 0 : break;
1285 : :
1286 : 0 : default:
1287 : 0 : actx_error(actx, "could not update epoll set: %m");
1288 : : }
1289 : :
1290 : 0 : return -1;
1291 : : }
1292 : :
198 dgustafsson@postgres 1293 :CBC 449 : 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 : : */
1398 : : static bool
29 jchampion@postgresql 1399 : 1405 : comb_multiplexer(struct async_ctx *actx)
1400 : : {
1401 : : #if defined(HAVE_SYS_EPOLL_H)
1402 : : /* The epoll implementation doesn't hold onto stale events. */
1403 : 1405 : 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 : : */
1446 : : static bool
198 dgustafsson@postgres 1447 : 322 : set_timer(struct async_ctx *actx, long timeout)
1448 : : {
1449 : : #if defined(HAVE_SYS_EPOLL_H)
1450 : 322 : struct itimerspec spec = {0};
1451 : :
1452 [ + + ]: 322 : if (timeout < 0)
1453 : : {
1454 : : /* the zero itimerspec will disarm the timer below */
1455 : : }
1456 [ + + ]: 162 : 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 : 158 : spec.it_value.tv_nsec = 1;
1464 : : }
1465 : : else
1466 : : {
1467 : 4 : spec.it_value.tv_sec = timeout / 1000;
1468 : 4 : spec.it_value.tv_nsec = (timeout % 1000) * 1000000;
1469 : : }
1470 : :
1471 [ - + ]: 322 : if (timerfd_settime(actx->timerfd, 0 /* no flags */ , &spec, NULL) < 0)
1472 : : {
198 dgustafsson@postgres 1473 :UBC 0 : actx_error(actx, "setting timerfd to %ld: %m", timeout);
1474 : 0 : return false;
1475 : : }
1476 : :
198 dgustafsson@postgres 1477 :CBC 322 : 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 : : */
1543 : : static int
1544 : 492870 : timer_expired(struct async_ctx *actx)
1545 : : {
1546 : : #if defined(HAVE_SYS_EPOLL_H) || defined(HAVE_SYS_EVENT_H)
1547 : : int res;
1548 : :
1549 : : /* Is the timer ready? */
1550 : 492870 : res = PQsocketPoll(actx->timerfd, 1 /* forRead */ , 0, 0);
1551 [ - + ]: 492870 : if (res < 0)
1552 : : {
29 jchampion@postgresql 1553 :UBC 0 : actx_error(actx, "checking timer expiration: %m");
198 dgustafsson@postgres 1554 : 0 : return -1;
1555 : : }
1556 : :
198 dgustafsson@postgres 1557 :CBC 492870 : 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 : : */
1567 : : static int
1568 : 148 : register_timer(CURLM *curlm, long timeout, void *ctx)
1569 : : {
1570 : 148 : 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 [ - + ]: 148 : if (!set_timer(actx, timeout))
198 dgustafsson@postgres 1580 :UBC 0 : return -1; /* actx_error already called */
1581 : :
198 dgustafsson@postgres 1582 :CBC 148 : 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 : : */
1589 : : static bool
29 jchampion@postgresql 1590 : 492860 : drain_timer_events(struct async_ctx *actx, bool *was_expired)
1591 : : {
1592 : : int res;
1593 : :
1594 : 492860 : res = timer_expired(actx);
1595 [ - + ]: 492860 : if (res < 0)
29 jchampion@postgresql 1596 :UBC 0 : return false;
1597 : :
29 jchampion@postgresql 1598 [ + + ]:CBC 492860 : 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 [ - + ]: 159 : if (!set_timer(actx, -1))
29 jchampion@postgresql 1606 :UBC 0 : return false;
1607 : : }
1608 : :
29 jchampion@postgresql 1609 [ + + ]:CBC 492860 : if (was_expired)
1610 : 491315 : *was_expired = (res > 0);
1611 : :
1612 : 492860 : 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 : : */
1621 : : static int
198 dgustafsson@postgres 1622 : 2024 : debug_callback(CURL *handle, curl_infotype type, char *data, size_t size,
1623 : : void *clientp)
1624 : : {
1625 : : const char *prefix;
1626 : 2024 : bool printed_prefix = false;
1627 : : PQExpBufferData buf;
1628 : :
1629 : : /* Prefixes are modeled off of the default libcurl debug output. */
1630 [ + + + - ]: 2024 : switch (type)
1631 : : {
1632 : 708 : case CURLINFO_TEXT:
1633 : 708 : prefix = "*";
1634 : 708 : break;
1635 : :
1636 : 1068 : case CURLINFO_HEADER_IN: /* fall through */
1637 : : case CURLINFO_DATA_IN:
1638 : 1068 : prefix = "<";
1639 : 1068 : break;
1640 : :
1641 : 248 : case CURLINFO_HEADER_OUT: /* fall through */
1642 : : case CURLINFO_DATA_OUT:
1643 : 248 : prefix = ">";
1644 : 248 : break;
1645 : :
198 dgustafsson@postgres 1646 :UBC 0 : default:
1647 : 0 : return 0;
1648 : : }
1649 : :
198 dgustafsson@postgres 1650 :CBC 2024 : initPQExpBuffer(&buf);
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 [ + + ]: 656682 : for (int i = 0; i < size; i++)
1658 : : {
1659 : 654658 : char c = data[i];
1660 : :
1661 [ + + ]: 654658 : if (!printed_prefix)
1662 : : {
1663 : 2534 : appendPQExpBuffer(&buf, "[libcurl] %s ", prefix);
1664 : 2534 : printed_prefix = true;
1665 : : }
1666 : :
1667 [ + + + - ]: 654658 : if (c >= 0x20 && c <= 0x7E)
1668 : 650854 : appendPQExpBufferChar(&buf, c);
1669 [ + + ]: 3804 : else if ((type == CURLINFO_HEADER_IN
1670 [ + + ]: 2024 : || type == CURLINFO_HEADER_OUT
1671 [ + - ]: 708 : || type == CURLINFO_TEXT)
1672 [ + + + + ]: 3804 : && (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 : 4 : appendPQExpBuffer(&buf, "<%02X>", c);
1681 : :
1682 [ + + ]: 654658 : if (c == '\n')
1683 : : {
1684 : 2254 : appendPQExpBufferChar(&buf, c);
1685 : 2254 : printed_prefix = false;
1686 : : }
1687 : : }
1688 : :
1689 [ + + ]: 2024 : if (printed_prefix)
1690 : 280 : appendPQExpBufferChar(&buf, '\n'); /* finish the line */
1691 : :
1692 : 2024 : fprintf(stderr, "%s", buf.data);
1693 : 2024 : termPQExpBuffer(&buf);
1694 : 2024 : 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 : : */
1704 : : static bool
1705 : 48 : setup_curl_handles(struct async_ctx *actx)
1706 : : {
1707 : : /*
1708 : : * Create our multi handle. This encapsulates the entire conversation with
1709 : : * libcurl for this connection.
1710 : : */
1711 : 48 : actx->curlm = curl_multi_init();
1712 [ - + ]: 48 : if (!actx->curlm)
1713 : : {
1714 : : /* We don't get a lot of feedback on the failure reason. */
198 dgustafsson@postgres 1715 :UBC 0 : actx_error(actx, "failed to create libcurl multi handle");
1716 : 0 : 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 : : */
198 dgustafsson@postgres 1723 [ - + ]:CBC 48 : CHECK_MSETOPT(actx, CURLMOPT_SOCKETFUNCTION, register_socket, return false);
1724 [ - + ]: 48 : CHECK_MSETOPT(actx, CURLMOPT_SOCKETDATA, actx, return false);
1725 [ - + ]: 48 : CHECK_MSETOPT(actx, CURLMOPT_TIMERFUNCTION, register_timer, return false);
1726 [ - + ]: 48 : 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 : 48 : actx->curl = curl_easy_init();
1733 [ - + ]: 48 : if (!actx->curl)
1734 : : {
198 dgustafsson@postgres 1735 :UBC 0 : actx_error(actx, "failed to create libcurl handle");
1736 : 0 : 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 : : */
198 dgustafsson@postgres 1754 [ - + ]:CBC 48 : CHECK_SETOPT(actx, CURLOPT_NOSIGNAL, 1L, return false);
1755 : :
1756 [ + - ]: 48 : 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 [ - + ]: 48 : CHECK_SETOPT(actx, CURLOPT_DEBUGFUNCTION, debug_callback, return false);
1764 [ - + ]: 48 : CHECK_SETOPT(actx, CURLOPT_VERBOSE, 1L, return false);
1765 : : }
1766 : :
1767 [ - + ]: 48 : 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 : 48 : const CURLoption popt = CURLOPT_PROTOCOLS_STR;
1780 : 48 : const char *protos = "https";
1781 : 48 : 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 [ + - ]: 48 : if (actx->debugging)
1789 : 48 : protos = unsafe;
1790 : :
1791 [ - + ]: 48 : 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 [ + - ]: 48 : if (actx->debugging)
1803 : : {
1804 : : const char *env;
1805 : :
1806 [ - + ]: 48 : if ((env = getenv("PGOAUTHCAFILE")) != NULL)
198 dgustafsson@postgres 1807 [ # # ]:UBC 0 : 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 : : */
198 dgustafsson@postgres 1816 :CBC 48 : actx->headers = curl_slist_append(actx->headers, "Accept:");
1817 [ - + ]: 48 : if (actx->headers == NULL)
1818 : : {
198 dgustafsson@postgres 1819 :UBC 0 : actx_error(actx, "out of memory");
1820 : 0 : return false;
1821 : : }
198 dgustafsson@postgres 1822 [ - + ]:CBC 48 : CHECK_SETOPT(actx, CURLOPT_HTTPHEADER, actx->headers, return false);
1823 : :
1824 : 48 : 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 : : */
1837 : : static size_t
1838 : 180 : append_data(char *buf, size_t size, size_t nmemb, void *userdata)
1839 : : {
1840 : 180 : struct async_ctx *actx = userdata;
1841 : 180 : PQExpBuffer resp = &actx->work_data;
1842 : 180 : size_t len = size * nmemb;
1843 : :
1844 : : /* In case we receive data over the threshold, abort the transfer */
1845 [ + + ]: 180 : if ((resp->len + len) > MAX_OAUTH_RESPONSE_SIZE)
1846 : : {
1847 : 2 : actx_error(actx, "response is too large");
1848 : 2 : return 0;
1849 : : }
1850 : :
1851 : : /* The data passed from libcurl is not null-terminated */
1852 : 178 : appendBinaryPQExpBuffer(resp, buf, len);
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 [ + - - + ]: 178 : if (PQExpBufferBroken(resp))
1859 : : {
198 dgustafsson@postgres 1860 :UBC 0 : actx_error(actx, "out of memory");
1861 : 0 : return 0;
1862 : : }
1863 : :
198 dgustafsson@postgres 1864 :CBC 178 : 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 : : */
1877 : : static bool
1878 : 148 : start_request(struct async_ctx *actx)
1879 : : {
1880 : : CURLMcode err;
1881 : :
1882 : 148 : resetPQExpBuffer(&actx->work_data);
1883 [ - + ]: 148 : CHECK_SETOPT(actx, CURLOPT_WRITEFUNCTION, append_data, return false);
1884 [ - + ]: 148 : CHECK_SETOPT(actx, CURLOPT_WRITEDATA, actx, return false);
1885 : :
1886 : 148 : err = curl_multi_add_handle(actx->curlm, actx->curl);
1887 [ - + ]: 148 : if (err)
1888 : : {
198 dgustafsson@postgres 1889 :UBC 0 : actx_error(actx, "failed to queue HTTP request: %s",
1890 : : curl_multi_strerror(err));
1891 : 0 : 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 : : */
198 dgustafsson@postgres 1903 :CBC 148 : err = curl_multi_socket_action(actx->curlm, CURL_SOCKET_TIMEOUT, 0, &actx->running);
1904 [ - + ]: 148 : if (err)
1905 : : {
198 dgustafsson@postgres 1906 :UBC 0 : actx_error(actx, "asynchronous HTTP request failed: %s",
1907 : : curl_multi_strerror(err));
1908 : 0 : return false;
1909 : : }
1910 : :
198 dgustafsson@postgres 1911 :CBC 148 : return true;
1912 : : }
1913 : :
1914 : : /*
1915 : : * CURL_IGNORE_DEPRECATION was added in 7.87.0. If it's not defined, we can make
1916 : : * it a no-op.
1917 : : */
1918 : : #ifndef CURL_IGNORE_DEPRECATION
1919 : : #define CURL_IGNORE_DEPRECATION(x) x
1920 : : #endif
1921 : :
1922 : : /*
1923 : : * Drives the multi handle towards completion. The caller should have already
1924 : : * set up an asynchronous request via start_request().
1925 : : */
1926 : : static PostgresPollingStatusType
1927 : 1545 : drive_request(struct async_ctx *actx)
1928 : : {
1929 : : CURLMcode err;
1930 : : CURLMsg *msg;
1931 : : int msgs_left;
1932 : : bool done;
1933 : :
1934 [ + - ]: 1545 : if (actx->running)
1935 : : {
1936 : : /*---
1937 : : * There's an async request in progress. Pump the multi handle.
1938 : : *
1939 : : * curl_multi_socket_all() is officially deprecated, because it's
1940 : : * inefficient and pointless if your event loop has already handed you
1941 : : * the exact sockets that are ready. But that's not our use case --
1942 : : * our client has no way to tell us which sockets are ready. (They
1943 : : * don't even know there are sockets to begin with.)
1944 : : *
1945 : : * We can grab the list of triggered events from the multiplexer
1946 : : * ourselves, but that's effectively what curl_multi_socket_all() is
1947 : : * going to do. And there are currently no plans for the Curl project
1948 : : * to remove or break this API, so ignore the deprecation. See
1949 : : *
1950 : : * https://curl.se/mail/lib-2024-11/0028.html
1951 : : *
1952 : : */
1953 : 1545 : CURL_IGNORE_DEPRECATION(
1954 : : err = curl_multi_socket_all(actx->curlm, &actx->running);
1955 : : )
1956 : :
1957 [ - + ]: 1545 : if (err)
1958 : : {
198 dgustafsson@postgres 1959 :UBC 0 : actx_error(actx, "asynchronous HTTP request failed: %s",
1960 : : curl_multi_strerror(err));
1961 : 0 : return PGRES_POLLING_FAILED;
1962 : : }
1963 : :
198 dgustafsson@postgres 1964 [ + + ]:CBC 1545 : if (actx->running)
1965 : : {
1966 : : /* We'll come back again. */
1967 : 1397 : return PGRES_POLLING_READING;
1968 : : }
1969 : : }
1970 : :
1971 : 148 : done = false;
1972 [ + + ]: 294 : while ((msg = curl_multi_info_read(actx->curlm, &msgs_left)) != NULL)
1973 : : {
1974 [ - + ]: 148 : if (msg->msg != CURLMSG_DONE)
1975 : : {
1976 : : /*
1977 : : * Future libcurl versions may define new message types; we don't
1978 : : * know how to handle them, so we'll ignore them.
1979 : : */
198 dgustafsson@postgres 1980 :UBC 0 : continue;
1981 : : }
1982 : :
1983 : : /* First check the status of the request itself. */
198 dgustafsson@postgres 1984 [ + + ]:CBC 148 : if (msg->data.result != CURLE_OK)
1985 : : {
1986 : : /*
1987 : : * If a more specific error hasn't already been reported, use
1988 : : * libcurl's description.
1989 : : */
1990 [ - + ]: 2 : if (actx->errbuf.len == 0)
198 dgustafsson@postgres 1991 :UBC 0 : actx_error_str(actx, curl_easy_strerror(msg->data.result));
1992 : :
198 dgustafsson@postgres 1993 :CBC 2 : return PGRES_POLLING_FAILED;
1994 : : }
1995 : :
1996 : : /* Now remove the finished handle; we'll add it back later if needed. */
1997 : 146 : err = curl_multi_remove_handle(actx->curlm, msg->easy_handle);
1998 [ - + ]: 146 : if (err)
1999 : : {
198 dgustafsson@postgres 2000 :UBC 0 : actx_error(actx, "libcurl easy handle removal failed: %s",
2001 : : curl_multi_strerror(err));
2002 : 0 : return PGRES_POLLING_FAILED;
2003 : : }
2004 : :
198 dgustafsson@postgres 2005 :CBC 146 : done = true;
2006 : : }
2007 : :
2008 : : /* Sanity check. */
2009 [ - + ]: 146 : if (!done)
2010 : : {
198 dgustafsson@postgres 2011 :UBC 0 : actx_error(actx, "no result was retrieved for the finished handle");
2012 : 0 : return PGRES_POLLING_FAILED;
2013 : : }
2014 : :
198 dgustafsson@postgres 2015 :CBC 146 : return PGRES_POLLING_OK;
2016 : : }
2017 : :
2018 : : /*
2019 : : * URL-Encoding Helpers
2020 : : */
2021 : :
2022 : : /*
2023 : : * Encodes a string using the application/x-www-form-urlencoded format, and
2024 : : * appends it to the given buffer.
2025 : : */
2026 : : static void
2027 : 490 : append_urlencoded(PQExpBuffer buf, const char *s)
2028 : : {
2029 : : char *escaped;
2030 : : char *haystack;
2031 : : char *match;
2032 : :
2033 : : /* The first parameter to curl_easy_escape is deprecated by Curl */
2034 : 490 : escaped = curl_easy_escape(NULL, s, 0);
2035 [ - + ]: 490 : if (!escaped)
2036 : : {
198 dgustafsson@postgres 2037 :UBC 0 : termPQExpBuffer(buf); /* mark the buffer broken */
2038 : 0 : return;
2039 : : }
2040 : :
2041 : : /*
2042 : : * curl_easy_escape() almost does what we want, but we need the
2043 : : * query-specific flavor which uses '+' instead of '%20' for spaces. The
2044 : : * Curl command-line tool does this with a simple search-and-replace, so
2045 : : * follow its lead.
2046 : : */
198 dgustafsson@postgres 2047 :CBC 490 : haystack = escaped;
2048 : :
2049 [ + + ]: 549 : while ((match = strstr(haystack, "%20")) != NULL)
2050 : : {
2051 : : /* Append the unmatched portion, followed by the plus sign. */
2052 : 59 : appendBinaryPQExpBuffer(buf, haystack, match - haystack);
2053 : 59 : appendPQExpBufferChar(buf, '+');
2054 : :
2055 : : /* Keep searching after the match. */
2056 : 59 : haystack = match + 3 /* strlen("%20") */ ;
2057 : : }
2058 : :
2059 : : /* Push the remainder of the string onto the buffer. */
2060 : 490 : appendPQExpBufferStr(buf, haystack);
2061 : :
2062 : 490 : curl_free(escaped);
2063 : : }
2064 : :
2065 : : /*
2066 : : * Convenience wrapper for encoding a single string. Returns NULL on allocation
2067 : : * failure.
2068 : : */
2069 : : static char *
2070 : 28 : urlencode(const char *s)
2071 : : {
2072 : : PQExpBufferData buf;
2073 : :
2074 : 28 : initPQExpBuffer(&buf);
2075 : 28 : append_urlencoded(&buf, s);
2076 : :
2077 [ + - ]: 28 : return PQExpBufferDataBroken(buf) ? NULL : buf.data;
2078 : : }
2079 : :
2080 : : /*
2081 : : * Appends a key/value pair to the end of an application/x-www-form-urlencoded
2082 : : * list.
2083 : : */
2084 : : static void
2085 : 231 : build_urlencoded(PQExpBuffer buf, const char *key, const char *value)
2086 : : {
2087 [ + + ]: 231 : if (buf->len)
2088 : 131 : appendPQExpBufferChar(buf, '&');
2089 : :
2090 : 231 : append_urlencoded(buf, key);
2091 : 231 : appendPQExpBufferChar(buf, '=');
2092 : 231 : append_urlencoded(buf, value);
2093 : 231 : }
2094 : :
2095 : : /*
2096 : : * Specific HTTP Request Handlers
2097 : : *
2098 : : * This is finally the beginning of the actual application logic. Generally
2099 : : * speaking, a single request consists of a start_* and a finish_* step, with
2100 : : * drive_request() pumping the machine in between.
2101 : : */
2102 : :
2103 : : /*
2104 : : * Queue an OpenID Provider Configuration Request:
2105 : : *
2106 : : * https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfigurationRequest
2107 : : * https://www.rfc-editor.org/rfc/rfc8414#section-3.1
2108 : : *
2109 : : * This is done first to get the endpoint URIs we need to contact and to make
2110 : : * sure the provider provides a device authorization flow. finish_discovery()
2111 : : * will fill in actx->provider.
2112 : : */
2113 : : static bool
2114 : 48 : start_discovery(struct async_ctx *actx, const char *discovery_uri)
2115 : : {
2116 [ - + ]: 48 : CHECK_SETOPT(actx, CURLOPT_HTTPGET, 1L, return false);
2117 [ - + ]: 48 : CHECK_SETOPT(actx, CURLOPT_URL, discovery_uri, return false);
2118 : :
2119 : 48 : return start_request(actx);
2120 : : }
2121 : :
2122 : : static bool
2123 : 48 : finish_discovery(struct async_ctx *actx)
2124 : : {
2125 : : long response_code;
2126 : :
2127 : : /*----
2128 : : * Now check the response. OIDC Discovery 1.0 is pretty strict:
2129 : : *
2130 : : * A successful response MUST use the 200 OK HTTP status code and
2131 : : * return a JSON object using the application/json content type that
2132 : : * contains a set of Claims as its members that are a subset of the
2133 : : * Metadata values defined in Section 3.
2134 : : *
2135 : : * Compared to standard HTTP semantics, this makes life easy -- we don't
2136 : : * need to worry about redirections (which would call the Issuer host
2137 : : * validation into question), or non-authoritative responses, or any other
2138 : : * complications.
2139 : : */
2140 [ - + ]: 48 : CHECK_GETINFO(actx, CURLINFO_RESPONSE_CODE, &response_code, return false);
2141 : :
2142 [ - + ]: 48 : if (response_code != 200)
2143 : : {
198 dgustafsson@postgres 2144 :UBC 0 : actx_error(actx, "unexpected response code %ld", response_code);
2145 : 0 : return false;
2146 : : }
2147 : :
2148 : : /*
2149 : : * Pull the fields we care about from the document.
2150 : : */
198 dgustafsson@postgres 2151 :CBC 48 : actx->errctx = "failed to parse OpenID discovery document";
2152 [ - + ]: 48 : if (!parse_provider(actx, &actx->provider))
198 dgustafsson@postgres 2153 :UBC 0 : return false; /* error message already set */
2154 : :
2155 : : /*
2156 : : * Fill in any defaults for OPTIONAL/RECOMMENDED fields we care about.
2157 : : */
198 dgustafsson@postgres 2158 [ - + ]:CBC 48 : if (!actx->provider.grant_types_supported)
2159 : : {
2160 : : /*
2161 : : * Per Section 3, the default is ["authorization_code", "implicit"].
2162 : : */
198 dgustafsson@postgres 2163 :UBC 0 : struct curl_slist *temp = actx->provider.grant_types_supported;
2164 : :
2165 : 0 : temp = curl_slist_append(temp, "authorization_code");
2166 [ # # ]: 0 : if (temp)
2167 : : {
2168 : 0 : temp = curl_slist_append(temp, "implicit");
2169 : : }
2170 : :
2171 [ # # ]: 0 : if (!temp)
2172 : : {
2173 : 0 : actx_error(actx, "out of memory");
2174 : 0 : return false;
2175 : : }
2176 : :
2177 : 0 : actx->provider.grant_types_supported = temp;
2178 : : }
2179 : :
198 dgustafsson@postgres 2180 :CBC 48 : return true;
2181 : : }
2182 : :
2183 : : /*
2184 : : * Ensure that the discovery document is provided by the expected issuer.
2185 : : * Currently, issuers are statically configured in the connection string.
2186 : : */
2187 : : static bool
2188 : 48 : check_issuer(struct async_ctx *actx, PGconn *conn)
2189 : : {
2190 : 48 : const struct provider *provider = &actx->provider;
128 jchampion@postgresql 2191 : 48 : const char *oauth_issuer_id = conn_oauth_issuer_id(conn);
2192 : :
2193 [ - + ]: 48 : Assert(oauth_issuer_id); /* ensured by setup_oauth_parameters() */
198 dgustafsson@postgres 2194 [ - + ]: 48 : Assert(provider->issuer); /* ensured by parse_provider() */
2195 : :
2196 : : /*---
2197 : : * We require strict equality for issuer identifiers -- no path or case
2198 : : * normalization, no substitution of default ports and schemes, etc. This
2199 : : * is done to match the rules in OIDC Discovery Sec. 4.3 for config
2200 : : * validation:
2201 : : *
2202 : : * The issuer value returned MUST be identical to the Issuer URL that
2203 : : * was used as the prefix to /.well-known/openid-configuration to
2204 : : * retrieve the configuration information.
2205 : : *
2206 : : * as well as the rules set out in RFC 9207 for avoiding mix-up attacks:
2207 : : *
2208 : : * Clients MUST then [...] compare the result to the issuer identifier
2209 : : * of the authorization server where the authorization request was
2210 : : * sent to. This comparison MUST use simple string comparison as defined
2211 : : * in Section 6.2.1 of [RFC3986].
2212 : : */
128 jchampion@postgresql 2213 [ - + ]: 48 : if (strcmp(oauth_issuer_id, provider->issuer) != 0)
2214 : : {
198 dgustafsson@postgres 2215 :UBC 0 : actx_error(actx,
2216 : : "the issuer identifier (%s) does not match oauth_issuer (%s)",
2217 : : provider->issuer, oauth_issuer_id);
2218 : 0 : return false;
2219 : : }
2220 : :
198 dgustafsson@postgres 2221 :CBC 48 : return true;
2222 : : }
2223 : :
2224 : : #define HTTPS_SCHEME "https://"
2225 : : #define OAUTH_GRANT_TYPE_DEVICE_CODE "urn:ietf:params:oauth:grant-type:device_code"
2226 : :
2227 : : /*
2228 : : * Ensure that the provider supports the Device Authorization flow (i.e. it
2229 : : * provides an authorization endpoint, and both the token and authorization
2230 : : * endpoint URLs seem reasonable).
2231 : : */
2232 : : static bool
2233 : 48 : check_for_device_flow(struct async_ctx *actx)
2234 : : {
2235 : 48 : const struct provider *provider = &actx->provider;
2236 : :
2237 [ - + ]: 48 : Assert(provider->issuer); /* ensured by parse_provider() */
2238 [ - + ]: 48 : Assert(provider->token_endpoint); /* ensured by parse_provider() */
2239 : :
2240 [ - + ]: 48 : if (!provider->device_authorization_endpoint)
2241 : : {
198 dgustafsson@postgres 2242 :UBC 0 : actx_error(actx,
2243 : : "issuer \"%s\" does not provide a device authorization endpoint",
2244 : : provider->issuer);
2245 : 0 : return false;
2246 : : }
2247 : :
2248 : : /*
2249 : : * The original implementation checked that OAUTH_GRANT_TYPE_DEVICE_CODE
2250 : : * was present in the discovery document's grant_types_supported list. MS
2251 : : * Entra does not advertise this grant type, though, and since it doesn't
2252 : : * make sense to stand up a device_authorization_endpoint without also
2253 : : * accepting device codes at the token_endpoint, that's the only thing we
2254 : : * currently require.
2255 : : */
2256 : :
2257 : : /*
2258 : : * Although libcurl will fail later if the URL contains an unsupported
2259 : : * scheme, that error message is going to be a bit opaque. This is a
2260 : : * decent time to bail out if we're not using HTTPS for the endpoints
2261 : : * we'll use for the flow.
2262 : : */
198 dgustafsson@postgres 2263 [ - + ]:CBC 48 : if (!actx->debugging)
2264 : : {
198 dgustafsson@postgres 2265 [ # # ]:UBC 0 : if (pg_strncasecmp(provider->device_authorization_endpoint,
2266 : : HTTPS_SCHEME, strlen(HTTPS_SCHEME)) != 0)
2267 : : {
2268 : 0 : actx_error(actx,
2269 : : "device authorization endpoint \"%s\" must use HTTPS",
2270 : : provider->device_authorization_endpoint);
2271 : 0 : return false;
2272 : : }
2273 : :
2274 [ # # ]: 0 : if (pg_strncasecmp(provider->token_endpoint,
2275 : : HTTPS_SCHEME, strlen(HTTPS_SCHEME)) != 0)
2276 : : {
2277 : 0 : actx_error(actx,
2278 : : "token endpoint \"%s\" must use HTTPS",
2279 : : provider->token_endpoint);
2280 : 0 : return false;
2281 : : }
2282 : : }
2283 : :
198 dgustafsson@postgres 2284 :CBC 48 : return true;
2285 : : }
2286 : :
2287 : : /*
2288 : : * Adds the client ID (and secret, if provided) to the current request, using
2289 : : * either HTTP headers or the request body.
2290 : : */
2291 : : static bool
2292 : 100 : add_client_identification(struct async_ctx *actx, PQExpBuffer reqbody, PGconn *conn)
2293 : : {
128 jchampion@postgresql 2294 : 100 : const char *oauth_client_id = conn_oauth_client_id(conn);
2295 : 100 : const char *oauth_client_secret = conn_oauth_client_secret(conn);
2296 : :
198 dgustafsson@postgres 2297 : 100 : bool success = false;
2298 : 100 : char *username = NULL;
2299 : 100 : char *password = NULL;
2300 : :
128 jchampion@postgresql 2301 [ + + ]: 100 : if (oauth_client_secret) /* Zero-length secrets are permitted! */
2302 : : {
2303 : : /*----
2304 : : * Use HTTP Basic auth to send the client_id and secret. Per RFC 6749,
2305 : : * Sec. 2.3.1,
2306 : : *
2307 : : * Including the client credentials in the request-body using the
2308 : : * two parameters is NOT RECOMMENDED and SHOULD be limited to
2309 : : * clients unable to directly utilize the HTTP Basic authentication
2310 : : * scheme (or other password-based HTTP authentication schemes).
2311 : : *
2312 : : * Additionally:
2313 : : *
2314 : : * The client identifier is encoded using the
2315 : : * "application/x-www-form-urlencoded" encoding algorithm per Appendix
2316 : : * B, and the encoded value is used as the username; the client
2317 : : * password is encoded using the same algorithm and used as the
2318 : : * password.
2319 : : *
2320 : : * (Appendix B modifies application/x-www-form-urlencoded by requiring
2321 : : * an initial UTF-8 encoding step. Since the client ID and secret must
2322 : : * both be 7-bit ASCII -- RFC 6749 Appendix A -- we don't worry about
2323 : : * that in this function.)
2324 : : *
2325 : : * client_id is not added to the request body in this case. Not only
2326 : : * would it be redundant, but some providers in the wild (e.g. Okta)
2327 : : * refuse to accept it.
2328 : : */
2329 : 14 : username = urlencode(oauth_client_id);
2330 : 14 : password = urlencode(oauth_client_secret);
2331 : :
198 dgustafsson@postgres 2332 [ + - - + ]: 14 : if (!username || !password)
2333 : : {
198 dgustafsson@postgres 2334 :UBC 0 : actx_error(actx, "out of memory");
2335 : 0 : goto cleanup;
2336 : : }
2337 : :
198 dgustafsson@postgres 2338 [ - + ]:CBC 14 : CHECK_SETOPT(actx, CURLOPT_HTTPAUTH, CURLAUTH_BASIC, goto cleanup);
2339 [ - + ]: 14 : CHECK_SETOPT(actx, CURLOPT_USERNAME, username, goto cleanup);
2340 [ - + ]: 14 : CHECK_SETOPT(actx, CURLOPT_PASSWORD, password, goto cleanup);
2341 : :
2342 : 14 : actx->used_basic_auth = true;
2343 : : }
2344 : : else
2345 : : {
2346 : : /*
2347 : : * If we're not otherwise authenticating, client_id is REQUIRED in the
2348 : : * request body.
2349 : : */
128 jchampion@postgresql 2350 : 86 : build_urlencoded(reqbody, "client_id", oauth_client_id);
2351 : :
198 dgustafsson@postgres 2352 [ - + ]: 86 : CHECK_SETOPT(actx, CURLOPT_HTTPAUTH, CURLAUTH_NONE, goto cleanup);
2353 : 86 : actx->used_basic_auth = false;
2354 : : }
2355 : :
2356 : 100 : success = true;
2357 : :
2358 : 100 : cleanup:
2359 : 100 : free(username);
2360 : 100 : free(password);
2361 : :
2362 : 100 : return success;
2363 : : }
2364 : :
2365 : : /*
2366 : : * Queue a Device Authorization Request:
2367 : : *
2368 : : * https://www.rfc-editor.org/rfc/rfc8628#section-3.1
2369 : : *
2370 : : * This is the second step. We ask the provider to verify the end user out of
2371 : : * band and authorize us to act on their behalf; it will give us the required
2372 : : * nonces for us to later poll the request status, which we'll grab in
2373 : : * finish_device_authz().
2374 : : */
2375 : : static bool
2376 : 48 : start_device_authz(struct async_ctx *actx, PGconn *conn)
2377 : : {
128 jchampion@postgresql 2378 : 48 : const char *oauth_scope = conn_oauth_scope(conn);
198 dgustafsson@postgres 2379 : 48 : const char *device_authz_uri = actx->provider.device_authorization_endpoint;
2380 : 48 : PQExpBuffer work_buffer = &actx->work_data;
2381 : :
128 jchampion@postgresql 2382 [ - + ]: 48 : Assert(conn_oauth_client_id(conn)); /* ensured by setup_oauth_parameters() */
198 dgustafsson@postgres 2383 [ - + ]: 48 : Assert(device_authz_uri); /* ensured by check_for_device_flow() */
2384 : :
2385 : : /* Construct our request body. */
2386 : 48 : resetPQExpBuffer(work_buffer);
128 jchampion@postgresql 2387 [ + - + + ]: 48 : if (oauth_scope && oauth_scope[0])
2388 : 41 : build_urlencoded(work_buffer, "scope", oauth_scope);
2389 : :
198 dgustafsson@postgres 2390 [ - + ]: 48 : if (!add_client_identification(actx, work_buffer, conn))
198 dgustafsson@postgres 2391 :UBC 0 : return false;
2392 : :
198 dgustafsson@postgres 2393 [ + - - + ]:CBC 48 : if (PQExpBufferBroken(work_buffer))
2394 : : {
198 dgustafsson@postgres 2395 :UBC 0 : actx_error(actx, "out of memory");
2396 : 0 : return false;
2397 : : }
2398 : :
2399 : : /* Make our request. */
198 dgustafsson@postgres 2400 [ - + ]:CBC 48 : CHECK_SETOPT(actx, CURLOPT_URL, device_authz_uri, return false);
2401 [ - + ]: 48 : CHECK_SETOPT(actx, CURLOPT_COPYPOSTFIELDS, work_buffer->data, return false);
2402 : :
2403 : 48 : return start_request(actx);
2404 : : }
2405 : :
2406 : : static bool
2407 : 47 : finish_device_authz(struct async_ctx *actx)
2408 : : {
2409 : : long response_code;
2410 : :
2411 [ - + ]: 47 : CHECK_GETINFO(actx, CURLINFO_RESPONSE_CODE, &response_code, return false);
2412 : :
2413 : : /*
2414 : : * Per RFC 8628, Section 3, a successful device authorization response
2415 : : * uses 200 OK.
2416 : : */
2417 [ + - ]: 47 : if (response_code == 200)
2418 : : {
2419 : 47 : actx->errctx = "failed to parse device authorization";
2420 [ + + ]: 47 : if (!parse_device_authz(actx, &actx->authz))
2421 : 3 : return false; /* error message already set */
2422 : :
2423 : 44 : return true;
2424 : : }
2425 : :
2426 : : /*
2427 : : * The device authorization endpoint uses the same error response as the
2428 : : * token endpoint, so the error handling roughly follows
2429 : : * finish_token_request(). The key difference is that an error here is
2430 : : * immediately fatal.
2431 : : */
198 dgustafsson@postgres 2432 [ # # # # ]:UBC 0 : if (response_code == 400 || response_code == 401)
2433 : : {
2434 : 0 : struct token_error err = {0};
2435 : :
2436 [ # # ]: 0 : if (!parse_token_error(actx, &err))
2437 : : {
2438 : 0 : free_token_error(&err);
2439 : 0 : return false;
2440 : : }
2441 : :
2442 : : /* Copy the token error into the context error buffer */
2443 : 0 : record_token_error(actx, &err);
2444 : :
2445 : 0 : free_token_error(&err);
2446 : 0 : return false;
2447 : : }
2448 : :
2449 : : /* Any other response codes are considered invalid */
2450 : 0 : actx_error(actx, "unexpected response code %ld", response_code);
2451 : 0 : return false;
2452 : : }
2453 : :
2454 : : /*
2455 : : * Queue an Access Token Request:
2456 : : *
2457 : : * https://www.rfc-editor.org/rfc/rfc6749#section-4.1.3
2458 : : *
2459 : : * This is the final step. We continually poll the token endpoint to see if the
2460 : : * user has authorized us yet. finish_token_request() will pull either the token
2461 : : * or a (ideally temporary) error status from the provider.
2462 : : */
2463 : : static bool
198 dgustafsson@postgres 2464 :CBC 52 : start_token_request(struct async_ctx *actx, PGconn *conn)
2465 : : {
2466 : 52 : const char *token_uri = actx->provider.token_endpoint;
2467 : 52 : const char *device_code = actx->authz.device_code;
2468 : 52 : PQExpBuffer work_buffer = &actx->work_data;
2469 : :
128 jchampion@postgresql 2470 [ - + ]: 52 : Assert(conn_oauth_client_id(conn)); /* ensured by setup_oauth_parameters() */
198 dgustafsson@postgres 2471 [ - + ]: 52 : Assert(token_uri); /* ensured by parse_provider() */
2472 [ - + ]: 52 : Assert(device_code); /* ensured by parse_device_authz() */
2473 : :
2474 : : /* Construct our request body. */
2475 : 52 : resetPQExpBuffer(work_buffer);
2476 : 52 : build_urlencoded(work_buffer, "device_code", device_code);
2477 : 52 : build_urlencoded(work_buffer, "grant_type", OAUTH_GRANT_TYPE_DEVICE_CODE);
2478 : :
2479 [ - + ]: 52 : if (!add_client_identification(actx, work_buffer, conn))
198 dgustafsson@postgres 2480 :UBC 0 : return false;
2481 : :
198 dgustafsson@postgres 2482 [ + - - + ]:CBC 52 : if (PQExpBufferBroken(work_buffer))
2483 : : {
198 dgustafsson@postgres 2484 :UBC 0 : actx_error(actx, "out of memory");
2485 : 0 : return false;
2486 : : }
2487 : :
2488 : : /* Make our request. */
198 dgustafsson@postgres 2489 [ - + ]:CBC 52 : CHECK_SETOPT(actx, CURLOPT_URL, token_uri, return false);
2490 [ - + ]: 52 : CHECK_SETOPT(actx, CURLOPT_COPYPOSTFIELDS, work_buffer->data, return false);
2491 : :
2492 : 52 : return start_request(actx);
2493 : : }
2494 : :
2495 : : static bool
2496 : 51 : finish_token_request(struct async_ctx *actx, struct token *tok)
2497 : : {
2498 : : long response_code;
2499 : :
2500 [ - + ]: 51 : CHECK_GETINFO(actx, CURLINFO_RESPONSE_CODE, &response_code, return false);
2501 : :
2502 : : /*
2503 : : * Per RFC 6749, Section 5, a successful response uses 200 OK.
2504 : : */
2505 [ + + ]: 51 : if (response_code == 200)
2506 : : {
2507 : 36 : actx->errctx = "failed to parse access token response";
2508 [ + + ]: 36 : if (!parse_access_token(actx, tok))
2509 : 2 : return false; /* error message already set */
2510 : :
2511 : 34 : return true;
2512 : : }
2513 : :
2514 : : /*
2515 : : * An error response uses either 400 Bad Request or 401 Unauthorized.
2516 : : * There are references online to implementations using 403 for error
2517 : : * return which would violate the specification. For now we stick to the
2518 : : * specification but we might have to revisit this.
2519 : : */
2520 [ + + + - ]: 15 : if (response_code == 400 || response_code == 401)
2521 : : {
2522 [ - + ]: 15 : if (!parse_token_error(actx, &tok->err))
198 dgustafsson@postgres 2523 :UBC 0 : return false;
2524 : :
198 dgustafsson@postgres 2525 :CBC 15 : return true;
2526 : : }
2527 : :
2528 : : /* Any other response codes are considered invalid */
198 dgustafsson@postgres 2529 :UBC 0 : actx_error(actx, "unexpected response code %ld", response_code);
2530 : 0 : return false;
2531 : : }
2532 : :
2533 : : /*
2534 : : * Finishes the token request and examines the response. If the flow has
2535 : : * completed, a valid token will be returned via the parameter list. Otherwise,
2536 : : * the token parameter remains unchanged, and the caller needs to wait for
2537 : : * another interval (which will have been increased in response to a slow_down
2538 : : * message from the server) before starting a new token request.
2539 : : *
2540 : : * False is returned only for permanent error conditions.
2541 : : */
2542 : : static bool
198 dgustafsson@postgres 2543 :CBC 51 : handle_token_response(struct async_ctx *actx, char **token)
2544 : : {
2545 : 51 : bool success = false;
2546 : 51 : struct token tok = {0};
2547 : : const struct token_error *err;
2548 : :
2549 [ + + ]: 51 : if (!finish_token_request(actx, &tok))
2550 : 2 : goto token_cleanup;
2551 : :
2552 : : /* A successful token request gives either a token or an in-band error. */
2553 [ + + - + ]: 49 : Assert(tok.access_token || tok.err.error);
2554 : :
2555 [ + + ]: 49 : if (tok.access_token)
2556 : : {
2557 : 34 : *token = tok.access_token;
2558 : 34 : tok.access_token = NULL;
2559 : :
2560 : 34 : success = true;
2561 : 34 : goto token_cleanup;
2562 : : }
2563 : :
2564 : : /*
2565 : : * authorization_pending and slow_down are the only acceptable errors;
2566 : : * anything else and we bail. These are defined in RFC 8628, Sec. 3.5.
2567 : : */
2568 : 15 : err = &tok.err;
2569 [ + + ]: 15 : if (strcmp(err->error, "authorization_pending") != 0 &&
2570 [ + + ]: 7 : strcmp(err->error, "slow_down") != 0)
2571 : : {
2572 : 6 : record_token_error(actx, err);
2573 : 6 : goto token_cleanup;
2574 : : }
2575 : :
2576 : : /*
2577 : : * A slow_down error requires us to permanently increase our retry
2578 : : * interval by five seconds.
2579 : : */
2580 [ + + ]: 9 : if (strcmp(err->error, "slow_down") == 0)
2581 : : {
2582 : 1 : int prev_interval = actx->authz.interval;
2583 : :
2584 : 1 : actx->authz.interval += 5;
2585 [ + - ]: 1 : if (actx->authz.interval < prev_interval)
2586 : : {
2587 : 1 : actx_error(actx, "slow_down interval overflow");
2588 : 1 : goto token_cleanup;
2589 : : }
2590 : : }
2591 : :
2592 : 8 : success = true;
2593 : :
2594 : 51 : token_cleanup:
2595 : 51 : free_token(&tok);
2596 : 51 : return success;
2597 : : }
2598 : :
2599 : : /*
2600 : : * Displays a device authorization prompt for action by the end user, either via
2601 : : * the PQauthDataHook, or by a message on standard error if no hook is set.
2602 : : */
2603 : : static bool
2604 : 34 : prompt_user(struct async_ctx *actx, PGconn *conn)
2605 : : {
2606 : : int res;
2607 : 34 : PGpromptOAuthDevice prompt = {
2608 : 34 : .verification_uri = actx->authz.verification_uri,
2609 : 34 : .user_code = actx->authz.user_code,
2610 : 34 : .verification_uri_complete = actx->authz.verification_uri_complete,
2611 : 34 : .expires_in = actx->authz.expires_in,
2612 : : };
128 jchampion@postgresql 2613 : 34 : PQauthDataHook_type hook = PQgetAuthDataHook();
2614 : :
2615 : 34 : res = hook(PQAUTHDATA_PROMPT_OAUTH_DEVICE, conn, &prompt);
2616 : :
198 dgustafsson@postgres 2617 [ + - ]: 34 : if (!res)
2618 : : {
2619 : : /*
2620 : : * translator: The first %s is a URL for the user to visit in a
2621 : : * browser, and the second %s is a code to be copy-pasted there.
2622 : : */
2623 : 34 : fprintf(stderr, libpq_gettext("Visit %s and enter the code: %s\n"),
2624 : : prompt.verification_uri, prompt.user_code);
2625 : : }
198 dgustafsson@postgres 2626 [ # # ]:UBC 0 : else if (res < 0)
2627 : : {
2628 : 0 : actx_error(actx, "device prompt failed");
2629 : 0 : return false;
2630 : : }
2631 : :
198 dgustafsson@postgres 2632 :CBC 34 : return true;
2633 : : }
2634 : :
2635 : : /*
2636 : : * Calls curl_global_init() in a thread-safe way.
2637 : : *
2638 : : * libcurl has stringent requirements for the thread context in which you call
2639 : : * curl_global_init(), because it's going to try initializing a bunch of other
2640 : : * libraries (OpenSSL, Winsock, etc). Recent versions of libcurl have improved
2641 : : * the thread-safety situation, but there's a chicken-and-egg problem at
2642 : : * runtime: you can't check the thread safety until you've initialized libcurl,
2643 : : * which you can't do from within a thread unless you know it's thread-safe...
2644 : : *
2645 : : * Returns true if initialization was successful. Successful or not, this
2646 : : * function will not try to reinitialize Curl on successive calls.
2647 : : */
2648 : : static bool
2649 : 492904 : initialize_curl(PGconn *conn)
2650 : : {
2651 : : /*
2652 : : * Don't let the compiler play tricks with this variable. In the
2653 : : * HAVE_THREADSAFE_CURL_GLOBAL_INIT case, we don't care if two threads
2654 : : * enter simultaneously, but we do care if this gets set transiently to
2655 : : * PG_BOOL_YES/NO in cases where that's not the final answer.
2656 : : */
2657 : : static volatile PGTernaryBool init_successful = PG_BOOL_UNKNOWN;
2658 : : #if HAVE_THREADSAFE_CURL_GLOBAL_INIT
2659 : : curl_version_info_data *info;
2660 : : #endif
2661 : :
2662 : : #if !HAVE_THREADSAFE_CURL_GLOBAL_INIT
2663 : :
2664 : : /*
2665 : : * Lock around the whole function. If a libpq client performs its own work
2666 : : * with libcurl, it must either ensure that Curl is initialized safely
2667 : : * before calling us (in which case our call will be a no-op), or else it
2668 : : * must guard its own calls to curl_global_init() with a registered
2669 : : * threadlock handler. See PQregisterThreadLock().
2670 : : */
2671 : : pglock_thread();
2672 : : #endif
2673 : :
2674 : : /*
2675 : : * Skip initialization if we've already done it. (Curl tracks the number
2676 : : * of calls; there's no point in incrementing the counter every time we
2677 : : * connect.)
2678 : : */
2679 [ + + ]: 492904 : if (init_successful == PG_BOOL_YES)
2680 : 492856 : goto done;
2681 [ - + ]: 48 : else if (init_successful == PG_BOOL_NO)
2682 : : {
198 dgustafsson@postgres 2683 :UBC 0 : libpq_append_conn_error(conn,
2684 : : "curl_global_init previously failed during OAuth setup");
2685 : 0 : goto done;
2686 : : }
2687 : :
2688 : : /*
2689 : : * We know we've already initialized Winsock by this point (see
2690 : : * pqMakeEmptyPGconn()), so we should be able to safely skip that bit. But
2691 : : * we have to tell libcurl to initialize everything else, because other
2692 : : * pieces of our client executable may already be using libcurl for their
2693 : : * own purposes. If we initialize libcurl with only a subset of its
2694 : : * features, we could break those other clients nondeterministically, and
2695 : : * that would probably be a nightmare to debug.
2696 : : *
2697 : : * If some other part of the program has already called this, it's a
2698 : : * no-op.
2699 : : */
198 dgustafsson@postgres 2700 [ - + ]:CBC 48 : if (curl_global_init(CURL_GLOBAL_ALL & ~CURL_GLOBAL_WIN32) != CURLE_OK)
2701 : : {
198 dgustafsson@postgres 2702 :UBC 0 : libpq_append_conn_error(conn,
2703 : : "curl_global_init failed during OAuth setup");
2704 : 0 : init_successful = PG_BOOL_NO;
2705 : 0 : goto done;
2706 : : }
2707 : :
2708 : : #if HAVE_THREADSAFE_CURL_GLOBAL_INIT
2709 : :
2710 : : /*
2711 : : * If we determined at configure time that the Curl installation is
2712 : : * thread-safe, our job here is much easier. We simply initialize above
2713 : : * without any locking (concurrent or duplicated calls are fine in that
2714 : : * situation), then double-check to make sure the runtime setting agrees,
2715 : : * to try to catch silent downgrades.
2716 : : */
198 dgustafsson@postgres 2717 :CBC 48 : info = curl_version_info(CURLVERSION_NOW);
2718 [ - + ]: 48 : if (!(info->features & CURL_VERSION_THREADSAFE))
2719 : : {
2720 : : /*
2721 : : * In a downgrade situation, the damage is already done. Curl global
2722 : : * state may be corrupted. Be noisy.
2723 : : */
198 dgustafsson@postgres 2724 :UBC 0 : libpq_append_conn_error(conn, "libcurl is no longer thread-safe\n"
2725 : : "\tCurl initialization was reported thread-safe when libpq\n"
2726 : : "\twas compiled, but the currently installed version of\n"
2727 : : "\tlibcurl reports that it is not. Recompile libpq against\n"
2728 : : "\tthe installed version of libcurl.");
2729 : 0 : init_successful = PG_BOOL_NO;
2730 : 0 : goto done;
2731 : : }
2732 : : #endif
2733 : :
198 dgustafsson@postgres 2734 :CBC 48 : init_successful = PG_BOOL_YES;
2735 : :
2736 : 492904 : done:
2737 : : #if !HAVE_THREADSAFE_CURL_GLOBAL_INIT
2738 : : pgunlock_thread();
2739 : : #endif
2740 : 492904 : return (init_successful == PG_BOOL_YES);
2741 : : }
2742 : :
2743 : : /*
2744 : : * The core nonblocking libcurl implementation. This will be called several
2745 : : * times to pump the async engine.
2746 : : *
2747 : : * The architecture is based on PQconnectPoll(). The first half drives the
2748 : : * connection state forward as necessary, returning if we're not ready to
2749 : : * proceed to the next step yet. The second half performs the actual transition
2750 : : * between states.
2751 : : *
2752 : : * You can trace the overall OAuth flow through the second half. It's linear
2753 : : * until we get to the end, where we flip back and forth between
2754 : : * OAUTH_STEP_TOKEN_REQUEST and OAUTH_STEP_WAIT_INTERVAL to regularly ping the
2755 : : * provider.
2756 : : */
2757 : : static PostgresPollingStatusType
2758 : 492904 : pg_fe_run_oauth_flow_impl(PGconn *conn)
2759 : : {
128 jchampion@postgresql 2760 : 492904 : fe_oauth_state *state = conn_sasl_state(conn);
2761 : : struct async_ctx *actx;
2762 : 492904 : char *oauth_token = NULL;
2763 : : PQExpBuffer errbuf;
2764 : :
198 dgustafsson@postgres 2765 [ - + ]: 492904 : if (!initialize_curl(conn))
198 dgustafsson@postgres 2766 :UBC 0 : return PGRES_POLLING_FAILED;
2767 : :
198 dgustafsson@postgres 2768 [ + + ]:CBC 492904 : if (!state->async_ctx)
2769 : : {
2770 : : /*
2771 : : * Create our asynchronous state, and hook it into the upper-level
2772 : : * OAuth state immediately, so any failures below won't leak the
2773 : : * context allocation.
2774 : : */
2775 : 48 : actx = calloc(1, sizeof(*actx));
2776 [ - + ]: 48 : if (!actx)
2777 : : {
198 dgustafsson@postgres 2778 :UBC 0 : libpq_append_conn_error(conn, "out of memory");
2779 : 0 : return PGRES_POLLING_FAILED;
2780 : : }
2781 : :
198 dgustafsson@postgres 2782 :CBC 48 : actx->mux = PGINVALID_SOCKET;
2783 : 48 : actx->timerfd = -1;
2784 : :
2785 : : /* Should we enable unsafe features? */
2786 : 48 : actx->debugging = oauth_unsafe_debugging_enabled();
2787 : :
2788 : 48 : state->async_ctx = actx;
2789 : :
2790 : 48 : initPQExpBuffer(&actx->work_data);
2791 : 48 : initPQExpBuffer(&actx->errbuf);
2792 : :
2793 [ - + ]: 48 : if (!setup_multiplexer(actx))
198 dgustafsson@postgres 2794 :UBC 0 : goto error_return;
2795 : :
198 dgustafsson@postgres 2796 [ - + ]:CBC 48 : if (!setup_curl_handles(actx))
198 dgustafsson@postgres 2797 :UBC 0 : goto error_return;
2798 : : }
2799 : :
198 dgustafsson@postgres 2800 :CBC 492904 : actx = state->async_ctx;
2801 : :
2802 : : do
2803 : : {
2804 : : /* By default, the multiplexer is the altsock. Reassign as desired. */
128 jchampion@postgresql 2805 : 492904 : set_conn_altsock(conn, actx->mux);
2806 : :
198 dgustafsson@postgres 2807 [ + + + - ]: 492904 : switch (actx->step)
2808 : : {
2809 : 48 : case OAUTH_STEP_INIT:
2810 : 48 : break;
2811 : :
2812 : 1545 : case OAUTH_STEP_DISCOVERY:
2813 : : case OAUTH_STEP_DEVICE_AUTHORIZATION:
2814 : : case OAUTH_STEP_TOKEN_REQUEST:
2815 : : {
2816 : : PostgresPollingStatusType status;
2817 : :
2818 : : /*
2819 : : * Clear any expired timeout before calling back into
2820 : : * Curl. Curl is not guaranteed to do this for us, because
2821 : : * its API expects us to use single-shot (i.e.
2822 : : * edge-triggered) timeouts, and ours are level-triggered
2823 : : * via the mux.
2824 : : *
2825 : : * This can't be combined with the comb_multiplexer() call
2826 : : * below: we might accidentally clear a short timeout that
2827 : : * was both set and expired during the call to
2828 : : * drive_request().
2829 : : */
29 jchampion@postgresql 2830 [ - + ]: 1545 : if (!drain_timer_events(actx, NULL))
29 jchampion@postgresql 2831 :UBC 0 : goto error_return;
2832 : :
2833 : : /* Move the request forward. */
198 dgustafsson@postgres 2834 :CBC 1545 : status = drive_request(actx);
2835 : :
2836 [ + + ]: 1545 : if (status == PGRES_POLLING_FAILED)
2837 : 2 : goto error_return;
29 jchampion@postgresql 2838 [ + + ]: 1543 : else if (status == PGRES_POLLING_OK)
2839 : 146 : break; /* done! */
2840 : :
2841 : : /*
2842 : : * This request is still running.
2843 : : *
2844 : : * Make sure that stale events don't cause us to come back
2845 : : * early. (Currently, this can occur only with kqueue.) If
2846 : : * this is forgotten, the multiplexer can get stuck in a
2847 : : * signaled state and we'll burn CPU cycles pointlessly.
2848 : : */
2849 [ - + ]: 1397 : if (!comb_multiplexer(actx))
29 jchampion@postgresql 2850 :UBC 0 : goto error_return;
2851 : :
29 jchampion@postgresql 2852 :CBC 1397 : return status;
2853 : : }
2854 : :
198 dgustafsson@postgres 2855 : 491311 : case OAUTH_STEP_WAIT_INTERVAL:
2856 : : {
2857 : : bool expired;
2858 : :
2859 : : /*
2860 : : * The client application is supposed to wait until our
2861 : : * timer expires before calling PQconnectPoll() again, but
2862 : : * that might not happen. To avoid sending a token request
2863 : : * early, check the timer before continuing.
2864 : : */
29 jchampion@postgresql 2865 [ - + ]: 491311 : if (!drain_timer_events(actx, &expired))
29 jchampion@postgresql 2866 :UBC 0 : goto error_return;
2867 : :
29 jchampion@postgresql 2868 [ + + ]:CBC 491311 : if (!expired)
2869 : : {
2870 : 491303 : set_conn_altsock(conn, actx->timerfd);
2871 : 491303 : return PGRES_POLLING_READING;
2872 : : }
2873 : :
2874 : 8 : break;
2875 : : }
2876 : : }
2877 : :
2878 : : /*
2879 : : * Each case here must ensure that actx->running is set while we're
2880 : : * waiting on some asynchronous work. Most cases rely on
2881 : : * start_request() to do that for them.
2882 : : */
198 dgustafsson@postgres 2883 [ + + + + : 202 : switch (actx->step)
+ - ]
2884 : : {
2885 : 48 : case OAUTH_STEP_INIT:
2886 : 48 : actx->errctx = "failed to fetch OpenID discovery document";
128 jchampion@postgresql 2887 [ - + ]: 48 : if (!start_discovery(actx, conn_oauth_discovery_uri(conn)))
198 dgustafsson@postgres 2888 :UBC 0 : goto error_return;
2889 : :
198 dgustafsson@postgres 2890 :CBC 48 : actx->step = OAUTH_STEP_DISCOVERY;
2891 : 48 : break;
2892 : :
2893 : 48 : case OAUTH_STEP_DISCOVERY:
2894 [ - + ]: 48 : if (!finish_discovery(actx))
198 dgustafsson@postgres 2895 :UBC 0 : goto error_return;
2896 : :
198 dgustafsson@postgres 2897 [ - + ]:CBC 48 : if (!check_issuer(actx, conn))
198 dgustafsson@postgres 2898 :UBC 0 : goto error_return;
2899 : :
198 dgustafsson@postgres 2900 :CBC 48 : actx->errctx = "cannot run OAuth device authorization";
2901 [ - + ]: 48 : if (!check_for_device_flow(actx))
198 dgustafsson@postgres 2902 :UBC 0 : goto error_return;
2903 : :
198 dgustafsson@postgres 2904 :CBC 48 : actx->errctx = "failed to obtain device authorization";
2905 [ - + ]: 48 : if (!start_device_authz(actx, conn))
198 dgustafsson@postgres 2906 :UBC 0 : goto error_return;
2907 : :
198 dgustafsson@postgres 2908 :CBC 48 : actx->step = OAUTH_STEP_DEVICE_AUTHORIZATION;
2909 : 48 : break;
2910 : :
2911 : 47 : case OAUTH_STEP_DEVICE_AUTHORIZATION:
2912 [ + + ]: 47 : if (!finish_device_authz(actx))
2913 : 3 : goto error_return;
2914 : :
2915 : 44 : actx->errctx = "failed to obtain access token";
2916 [ - + ]: 44 : if (!start_token_request(actx, conn))
198 dgustafsson@postgres 2917 :UBC 0 : goto error_return;
2918 : :
198 dgustafsson@postgres 2919 :CBC 44 : actx->step = OAUTH_STEP_TOKEN_REQUEST;
2920 : 44 : break;
2921 : :
2922 : 51 : case OAUTH_STEP_TOKEN_REQUEST:
128 jchampion@postgresql 2923 [ + + ]: 51 : if (!handle_token_response(actx, &oauth_token))
198 dgustafsson@postgres 2924 : 9 : goto error_return;
2925 : :
2926 : : /*
2927 : : * Hook any oauth_token into the PGconn immediately so that
2928 : : * the allocation isn't lost in case of an error.
2929 : : */
128 jchampion@postgresql 2930 : 42 : set_conn_oauth_token(conn, oauth_token);
2931 : :
198 dgustafsson@postgres 2932 [ + + ]: 42 : if (!actx->user_prompted)
2933 : : {
2934 : : /*
2935 : : * Now that we know the token endpoint isn't broken, give
2936 : : * the user the login instructions.
2937 : : */
2938 [ - + ]: 34 : if (!prompt_user(actx, conn))
198 dgustafsson@postgres 2939 :UBC 0 : goto error_return;
2940 : :
198 dgustafsson@postgres 2941 :CBC 34 : actx->user_prompted = true;
2942 : : }
2943 : :
128 jchampion@postgresql 2944 [ + + ]: 42 : if (oauth_token)
198 dgustafsson@postgres 2945 : 34 : break; /* done! */
2946 : :
2947 : : /*
2948 : : * Wait for the required interval before issuing the next
2949 : : * request.
2950 : : */
2951 [ - + ]: 8 : if (!set_timer(actx, actx->authz.interval * 1000))
198 dgustafsson@postgres 2952 :UBC 0 : goto error_return;
2953 : :
2954 : : /*
2955 : : * No Curl requests are running, so we can simplify by having
2956 : : * the client wait directly on the timerfd rather than the
2957 : : * multiplexer.
2958 : : */
128 jchampion@postgresql 2959 :CBC 8 : set_conn_altsock(conn, actx->timerfd);
2960 : :
198 dgustafsson@postgres 2961 : 8 : actx->step = OAUTH_STEP_WAIT_INTERVAL;
2962 : 8 : actx->running = 1;
2963 : 8 : break;
2964 : :
2965 : 8 : case OAUTH_STEP_WAIT_INTERVAL:
2966 : 8 : actx->errctx = "failed to obtain access token";
2967 [ - + ]: 8 : if (!start_token_request(actx, conn))
198 dgustafsson@postgres 2968 :UBC 0 : goto error_return;
2969 : :
198 dgustafsson@postgres 2970 :CBC 8 : actx->step = OAUTH_STEP_TOKEN_REQUEST;
2971 : 8 : break;
2972 : : }
2973 : :
2974 : : /*
2975 : : * The vast majority of the time, if we don't have a token at this
2976 : : * point, actx->running will be set. But there are some corner cases
2977 : : * where we can immediately loop back around; see start_request().
2978 : : */
128 jchampion@postgresql 2979 [ + + - + ]: 190 : } while (!oauth_token && !actx->running);
2980 : :
2981 : : /* If we've stored a token, we're done. Otherwise come back later. */
2982 [ + + ]: 190 : return oauth_token ? PGRES_POLLING_OK : PGRES_POLLING_READING;
2983 : :
198 dgustafsson@postgres 2984 : 14 : error_return:
128 jchampion@postgresql 2985 : 14 : errbuf = conn_errorMessage(conn);
2986 : :
2987 : : /*
2988 : : * Assemble the three parts of our error: context, body, and detail. See
2989 : : * also the documentation for struct async_ctx.
2990 : : */
198 dgustafsson@postgres 2991 [ + - ]: 14 : if (actx->errctx)
128 jchampion@postgresql 2992 : 14 : appendPQExpBuffer(errbuf, "%s: ", libpq_gettext(actx->errctx));
2993 : :
198 dgustafsson@postgres 2994 [ - + ]: 14 : if (PQExpBufferDataBroken(actx->errbuf))
128 jchampion@postgresql 2995 :UBC 0 : appendPQExpBufferStr(errbuf, libpq_gettext("out of memory"));
2996 : : else
128 jchampion@postgresql 2997 :CBC 14 : appendPQExpBufferStr(errbuf, actx->errbuf.data);
2998 : :
198 dgustafsson@postgres 2999 [ + + ]: 14 : if (actx->curl_err[0])
3000 : : {
128 jchampion@postgresql 3001 : 2 : appendPQExpBuffer(errbuf, " (libcurl: %s)", actx->curl_err);
3002 : :
3003 : : /* Sometimes libcurl adds a newline to the error buffer. :( */
3004 [ + - - + ]: 2 : if (errbuf->len >= 2 && errbuf->data[errbuf->len - 2] == '\n')
3005 : : {
128 jchampion@postgresql 3006 :UBC 0 : errbuf->data[errbuf->len - 2] = ')';
3007 : 0 : errbuf->data[errbuf->len - 1] = '\0';
3008 : 0 : errbuf->len--;
3009 : : }
3010 : : }
3011 : :
128 jchampion@postgresql 3012 :CBC 14 : appendPQExpBufferChar(errbuf, '\n');
3013 : :
198 dgustafsson@postgres 3014 : 14 : return PGRES_POLLING_FAILED;
3015 : : }
3016 : :
3017 : : /*
3018 : : * The top-level entry point. This is a convenient place to put necessary
3019 : : * wrapper logic before handing off to the true implementation, above.
3020 : : */
3021 : : PostgresPollingStatusType
3022 : 492904 : pg_fe_run_oauth_flow(PGconn *conn)
3023 : : {
3024 : : PostgresPollingStatusType result;
29 jchampion@postgresql 3025 : 492904 : fe_oauth_state *state = conn_sasl_state(conn);
3026 : : struct async_ctx *actx;
3027 : : #ifndef WIN32
3028 : : sigset_t osigset;
3029 : : bool sigpipe_pending;
3030 : : bool masked;
3031 : :
3032 : : /*---
3033 : : * Ignore SIGPIPE on this thread during all Curl processing.
3034 : : *
3035 : : * Because we support multiple threads, we have to set up libcurl with
3036 : : * CURLOPT_NOSIGNAL, which disables its default global handling of
3037 : : * SIGPIPE. From the Curl docs:
3038 : : *
3039 : : * libcurl makes an effort to never cause such SIGPIPE signals to
3040 : : * trigger, but some operating systems have no way to avoid them and
3041 : : * even on those that have there are some corner cases when they may
3042 : : * still happen, contrary to our desire.
3043 : : *
3044 : : * Note that libcurl is also at the mercy of its DNS resolution and SSL
3045 : : * libraries; if any of them forget a MSG_NOSIGNAL then we're in trouble.
3046 : : * Modern platforms and libraries seem to get it right, so this is a
3047 : : * difficult corner case to exercise in practice, and unfortunately it's
3048 : : * not really clear whether it's necessary in all cases.
3049 : : */
198 dgustafsson@postgres 3050 : 492904 : masked = (pq_block_sigpipe(&osigset, &sigpipe_pending) == 0);
3051 : : #endif
3052 : :
3053 : 492904 : result = pg_fe_run_oauth_flow_impl(conn);
3054 : :
3055 : : /*
3056 : : * To assist with finding bugs in comb_multiplexer() and
3057 : : * drain_timer_events(), when we're in debug mode, track the total number
3058 : : * of calls to this function and print that at the end of the flow.
3059 : : *
3060 : : * Be careful that state->async_ctx could be NULL if early initialization
3061 : : * fails during the first call.
3062 : : */
29 jchampion@postgresql 3063 : 492904 : actx = state->async_ctx;
3064 [ - + - - ]: 492904 : Assert(actx || result == PGRES_POLLING_FAILED);
3065 : :
3066 [ + - + - ]: 492904 : if (actx && actx->debugging)
3067 : : {
3068 : 492904 : actx->dbg_num_calls++;
3069 [ + + + + ]: 492904 : if (result == PGRES_POLLING_OK || result == PGRES_POLLING_FAILED)
3070 : 48 : fprintf(stderr, "[libpq] total number of polls: %d\n",
3071 : : actx->dbg_num_calls);
3072 : : }
3073 : :
3074 : : #ifndef WIN32
198 dgustafsson@postgres 3075 [ + - ]: 492904 : if (masked)
3076 : : {
3077 : : /*
3078 : : * Undo the SIGPIPE mask. Assume we may have gotten EPIPE (we have no
3079 : : * way of knowing at this level).
3080 : : */
3081 : 492904 : pq_reset_sigpipe(&osigset, sigpipe_pending, true /* EPIPE, maybe */ );
3082 : : }
3083 : : #endif
3084 : :
3085 : 492904 : return result;
3086 : : }
|