Repository navigation
feat(auth): add OIDC and rotating bearer tokens - #165
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
Walkthrough
Pre-merge checks:
|
Native-backed OIDC device-flow sign-in and rotating Bearer-token providers for the Python client (`questdb.auth`, `oidc_auth=`, `bearer_token_provider=`), split out of #133 so the feature can be reviewed against `main` without the unrelated fixes of #160. The feature runs user callbacks (token providers, sign-in renderers) inside native calls, so this also carries the re-entry guards from #160 that keep such a callback from using an object a native call holds: - a sender rejects its methods while a native call borrows it, and from its own connection listener or error handler; - a `Buffer` that a native call is modifying rejects reads and writes; - a query cursor rejects same-thread re-entry during a native read, and finalizers reclaim cursors without blocking; - a DataFrame error keeps its class when a note is appended, so `except OidcError` still matches. Bumps c-questdb-client to the matching native change (questdb/c-questdb-client#228). The full history is on branch `ia_oidc_device_flow` (#133).
09f4d68 to
f5190be
Compare
`RecordBatchReader.from_stream` and a dict argument to `pa.record_batch` arrived in pyarrow 15, so ten OIDC tests failed on the linux-min-deps job (pyarrow 14.0.1). Import the stream through `_import_from_c_capsule` there, as `system_test.py` does, and build the batch from a list of arrays.
`_OIDC_MAIN_THREAD_IDENT` came from `threading.main_thread().ident`, which gevent's monkey-patching makes a greenlet id. On 64-bit Windows that does not fit an `unsigned long`, so `import questdb` after `monkey.patch_all()` raised OverflowError, failing `main`'s `test_scoped_calls_from_greenlets_on_one_thread` on both Windows jobs. Elsewhere it never matched the native `PyThread_get_thread_ident()` the main-thread checks compare it with, so under gevent no thread counted as the main one. Read the native ident when `get_native_id()`, which gevent leaves alone, says this is the main OS thread, and compare natively in `_tp_on_main_thread` too. Without gevent nothing changes.
Bump c-questdb-client from a038a0a7 to b3e8f361: 7.2.0, merged from main, and the OIDC branch's fixes since. Its new `questdb_token_sink_set_terminal_error` lets an application provider report a failure that retrying can never clear. Until now clients kept retrying every failure of a Python provider in the background, whatever its TokenUnavailableError said, so a provider that knew it could never succeed kept its senders, queries and pools reconnecting until the application closed them. A provider now raises QuestDBError with code InvalidApiCall to stop them, as a Rust provider returns `InvalidApiCall` and a C++ one throws `questdb::error` with `invalid_api_call`: a QWP/WebSocket sender, query or pool fails with ConfigError and stops reconnecting, and an ILP/HTTP flush fails at once. A TokenUnavailableError keeps its classification whatever its code. A RefreshingTokenProvider's source cannot report one: its sink refuses it, so the exception counts as retryable like any other, and closing the provider is what stops its clients. The bump also brings: - A RefreshingTokenProvider wrapped in a provider of one's own (`lambda: tokens.token()`) refreshes early on a 401 instead of handing the rejected token back until its scheduled refresh. - A 401 re-fetch no longer takes the rejected token back from a fetch another connection started, and a forced refresh no longer logs under the provider's state lock, which could deadlock. - A close drain, and a flush that waits out sf_append_deadline_millis on a full queue, name a failing reconnect when they time out, rather than reporting a bare timeout or advising a larger sf_max_total_bytes. An ACK-wait or close-drain timeout no longer carries a server rejection's sender_error, which marks a terminal error. Document the terminal failure, and that ILP/HTTP calls the provider on every flush, on the flushing thread. Test that each kind of client stops on it, that a source's stays retryable, and that wrapped refreshing providers refresh on a QWP/WebSocket or ILP/HTTP 401.
Bring in 6.0.0: row egress (iter_rows, columns), EXEC_DONE counts, per-query timeouts, the UUID byte order, and QWP row auto-flush that keeps frames within the frame cap. Both branches reworked the same re-entry guards, so the conflicts are resolved by combining them: - Callback dispatch depths use main's native per-thread table. Our Python thread-local and its global fast-path counter are dropped. - Sender.flush() keeps main's _flush_c_buf split. Our native-borrow guard and parked-signal delivery move into _flush_c_buf, which now takes the Buffer, so row() auto-flush publishes under them too. - Sender.row() keeps our refusal from the sender's own callbacks whatever the auto-flush mode. Main's narrower per-row check is redundant and dropped; its docstring and docs/sender.rst follow. - _CursorHandle takes main's pin/defer model and keeps our _native_in_flight / _check_not_driving guards and non-blocking finalizer reclaim. A busy reclaim now leaves the free to a pinned holder, which main's lease-finalised-mid-decode test needs. QueryResult.close() refuses same-thread re-entry but frees through _close(), so a close interrupted while it waits is finished by the worker. Main's row-stream pulls deliver parked OIDC signals like the other reader pulls. - test_ci_wiring expects our OIDC CI extras in the minimum-versions run: none of them depends on a pinned package. CHANGELOG: our entries move from the released 6.0.0 section to a new 6.1.0 (unreleased) section, worded against 6.0 instead of 5.0.
QWP/WebSocket row() reworded a failed auto-flush publish by calling the exception's class with QuestDBError's positional signature. The classes c_err_to_py now returns for token-provider and OIDC failures do not share it. TokenUnavailableError, OidcDeviceFlowError and OidcTimeoutError raised TypeError, which `except QuestDBError` misses: row() did that during an IdP outage that fills the store-and-forward queue, and after a RefreshingTokenProvider was closed. The other OidcError classes came back with a tuple as their message and their class's default code. Copy the instance instead, as _dataframe_call_error does. Also: - _dataframe raised the main-thread signal-deferral counter before a check that can refuse the call outside the try that lowers it. One refused re-entrant dataframe() then swallowed every later Ctrl-C a token callback parked, for the rest of the process. - Sender and QuestDB gained a __dict__ for the bearer-token holder, so a misspelt setting (sender.request_timeout = 5000) was stored and read back while configuring nothing. Refuse new names as before; Python subclasses keep their dictionary. - RefreshingTokenProvider.close(wait=True) could return before a source call that had already passed the closed check ran. Mark the call in progress before checking. - An on_rejected lookup that raised was reported as an internal AttributeError: the signal-handler snapshot started as a tuple. - Docs: list the rejected token-provider config keys under 6.1.0 breaking changes; the PG adapters raise whatever the provider raises, not always OidcError; bearer_token_provider is keyword-only too (conf.rst, Sender.from_env).
49e50f6 routed every attribute assignment on Sender and QuestDB through _setattr_without_dict, which stored the value with object.__setattr__. Before 3.13, CPython refuses that call ("can't apply this __setattr__ to ... object") on an instance whose class overrides the C-level setattr slot, as the Cython __setattr__ does. __cinit__ sets _bearer_token_provider that way, so neither class could be constructed on CPython 3.10-3.12, and every wheel and test job for those versions failed. CPython 3.13+ and PyPy do not make the check. Call PyObject_GenericSetAttr, the function object.__setattr__ wraps, directly. Cython's own setattr slot already calls it for deletes.
…he pool test_pooled_dataframe_does_not_spin_on_oidc_network_failure counted the listener's events only after leaving `with questdb.connect(...)`. The event is queued on the pool's dispatcher inbox before dataframe() raises, but delivery runs on the dispatcher thread, and closing the pool discards anything it has not delivered yet. On a loaded CI agent the dispatcher had not been scheduled before close, so the listener saw no event at all (cp312 manylinux aarch64: `AssertionError: 0 != 1`). Wait for the event while the pool is open, as the OIDC failover tests' `_run` helper already does, then pause briefly so a surplus event from a retrying call would still be counted before close discards it.
The "on mac" leg failed because DNS on the runner briefly stopped resolving the GitHub release host. The first two system-test classes to run, TestColumnIngressFailover and TestColumnIngressNarrowTypes, each spent 30s in getaddrinfo, got URLError ([Errno 8] nodename nor servname provided), and errored in setUpClass. The third class downloaded the same tarball a minute later and every remaining test passed. may_install_questdb() now retries a URLError up to four times with 1/2/4s backoff, and never retries an HTTP response such as a missing release asset. This is the same retry #160 carries (ac24653), ported verbatim so the two branches merge cleanly. The egress _exec timeout change from that commit is unrelated and is left out.
|
/azp run questdb.py-questdb-client-release |
|
Azure Pipelines successfully started running 1 pipeline(s). |
questdb's atexit hook closes the callback gate before logging.shutdown() and before any atexit callback registered ahead of `import questdb`. An ILP/HTTP flush from either, with a Python bearer_token_provider, therefore retried for retry_timeout, raised TokenUnavailableError and lost its rows. A token callback that the main thread makes from inside its own native call now still runs while the interpreter is not finalizing. Callbacks on native threads stay refused, so the docs now say to flush and close QWP/WebSocket clients, and anything that needs a token refresh, before the interpreter exits. RefreshingTokenProvider durations had no upper bound. close(wait=True) with a timeout above threading.TIMEOUT_MAX raised OverflowError instead of waiting, a duration beyond the uint64 millisecond range reached an undefined double-to-integer conversion, and a huge retry_after overflowed and lost the source's classification. Waits are now sliced and the conversions clamped. The CHANGELOG now lists every read-only call that raises during a native call, and QuestDB.from_conf as a bearer_token_provider entry point.
Sender gained an instance __dict__ to hold the bearer-token holder where PyPy's collector can see it. Cython allocates that dictionary in tp_new, and while an instance has one, CPython cannot cache the method lookup of `sender.row(...)`: every row took the generic lookup, with or without a provider, about 7 ns per call over ILP/HTTP and 18 ns over QWP/WebSocket. CPython now keeps the holder in a typed slot and drops the empty dictionary in __cinit__; PyPy keeps it in the dictionary as before. row() now runs its own-callback check whatever the auto-flush mode, so a process-wide count of callback dispatches in progress answers it first, and the full check runs only while one is. An ILP/HTTP Sender.dataframe() auto-flush calls a bearer_token_provider on the caller's thread, inside the native flush. The frame took that callback for its own Python, so the provider could drive the sender it was supplying -- new_buffer(), a flush of another buffer -- and nest a native flush inside the one that called it. Outside a frame the same calls were already refused. Token callbacks now count as callbacks there, as OIDC ones do. Two holes in the same guard are closed too: a nested flush cleared the sender's in-native flag for the rest of the frame instead of restoring it, and a nested Buffer.dataframe() or SenderTransaction.dataframe(), refused anyway, dropped the outer frame's buffer borrow on its way to the refusal. CHANGELOG: CredentialUnavailable reports bearer_token_provider failures too, including the terminal stop on InvalidApiCall (ConfigError).
_ReaderHandle gained a __dict__ and an object field to keep the token providers alive, which made it a GC type with a Cython tp_clear that puts None in its __dict__ slot. When the cyclic collector freed an unclosed QuestDB.reader() lease -- one held in a frame that also kept a caught exception, say -- it cleared the handle first, and the lease's __dealloc__ then closed the reader and wrote _bearer_token_provider through that None: SIGBUS or SIGSEGV on CPython 3.13 and 3.14, an unraisable SystemError before. Mark the handle no_gc_clear, as _CursorHandle and _TokenProviderHandle are. The providers it references have their own tp_clear, so cycles through it stay collectable. QuestDB.dataframe() and PooledSender.dataframe() borrowed again at once after a connect that had already been given the rest of the reconnect budget. Native ends such a connect early on a failure it does not retry for a caller that waits -- an application bearer_token_provider that returns an empty token, or one with a trailing newline -- so the call spun until reconnect_max_duration ran out (300 s by default), calling the provider thousands of times a second, where query(), an eager connect() and Sender.establish() fail after one call. A connect that had a retry budget and failed is now final for the call.
The token-provider guide and the BearerTokenProvider docstring said that clients keep retrying a provider failure in the background, whatever a TokenUnavailableError says. That holds for the background reconnects of a QWP/WebSocket sender, query or pool, but not for ILP/HTTP: a flush calls the provider on the flushing thread, retries a retryable failure for up to retry_timeout, fails at once on a permanent one, and then raises, discarding the rows in the sender's internal buffer as any failed flush does. A reader who trusted the background retry could log the error and lose those rows. Scope the claim to QWP/WebSocket reconnects, note that a waited-for connect honours the classification, describe the ILP/HTTP flush, and show how to keep a batch for a resend: build it in sender.new_buffer() and flush it with clear=False.
Sender.dataframe() over ws:: connects with its own clone of the sender's
options, so a close() from Python its plan build runs -- a logging
handler, an attrs read, an object cell -- does not stop it. With a
callable bearer_token_provider the close released the sender's only
reference to the provider's holder. That unregistered its callback id
while the clone still pulled tokens through it, so the call raised
TokenUnavailableError ("the token provider was released") and wrote
nothing, where the same sequence with token= or no auth completes. Keep
the holder alive for the call, as the dispatch context already is.
OidcDeviceAuth has a token() method, so it matches the BearerTokenProvider protocol and type checkers accept it as bearer_token_provider=, but clients refuse it there with TypeError: it must be attached as oidc_auth=. Say so on the protocol, and correct the PG-wire paragraph and the adapters' docstring, which said the adapters accept exactly what bearer_token_provider= accepts: they also take an OidcDeviceAuth.
Picks up questdb/c-questdb-client#228 commit 886b497f. OidcDeviceAuth.sign_in() no longer fails with OidcDeviceFlowError ("the identity provider rejected the request") when a token-endpoint poll reply is cut off after its status line: an early close or reset, or a body that stalls past the timeout. It keeps polling, as it already did when a poll got no reply at all, so a user still approving the code in the browser can finish signing in. A complete non-JSON reply is still a rejection.
OidcTestServer can now cut a token-endpoint reply off: an override body
wrapped in TruncatedBody is sent with the whole body's Content-Length, but
only its first half goes out before the connection closes.
The new test cuts off the first device-grant poll's authorization_pending
reply. With the previous native pin, 87a7ee12, sign_in() raised
OidcDeviceFlowError ("the IdP rejected the token request ... Peer
disconnected") after one poll. With 886b497f it polls again and signs in.
Picks up questdb/c-questdb-client#228 commits 7f2b01f1 and fab63e5b: - Senders that share a RefreshingTokenProvider all replay a 401 for the same token with its replacement. A rejection inside forced_min_interval got the rejected token straight back while the forced fetch was still running, so every ILP/HTTP flush but the first failed with AuthError and dropped its batch. - A device-flow sign-in no longer opens, links or QR-encodes a loopback https:// URL that a remote identity provider hands out. Only a loopback IdP may name a loopback target, over either scheme. The RefreshingTokenProvider.on_rejected() docstring and the comment on the fallback URL vetter say so.
…s ConfigError ExpiringToken(token, datetime.max.replace(tzinfo=timezone.utc)), the usual Python way to say that a token does not expire, was rejected as outside the datetime range, against the docstring: the expiry went through a float, which rounds past the last microsecond near the year 9999, and a provider whose source returned it never became ready, so every client failed after cold_wait. An aware datetime is now checked by its UTC instant and clamped to 9999-12-31T23:59:59.999Z, the latest instant native represents, as native clamps it. Epoch seconds and status times no longer go through the C library's gmtime, which on Windows stops at the year 3000. RefreshingTokenProvider(name=...) and on_rejected(token) raised a bare UnicodeEncodeError for a str with a lone surrogate, which `except QuestDBError` missed although the API documents every bad argument as a ConfigError. They now raise its ValueError, as OidcDeviceAuth does for the same input. ExpiringToken.expires_in's docstring now says that refresh_at is an instant, as for the constructor, not a delay like lifetime: a refresh_in passed as is reads as an instant in 1970, and the provider then refreshes every min_refresh_interval. Tests: test_the_latest_instant_means_no_expiry and the new surrogate cases in InvalidArgumentErrorTest fail without the fix.
With gevent, a token provider that waits on I/O suspends its greenlet
inside the token callback while the other greenlets on the main thread
run. The client counted those callbacks per OS thread, so it took every
greenlet for the suspended one:
- Interpreter exit hung for good when a greenlet was suspended in a
provider at exit. The exit hook waited for every admitted callback,
but the greenlet could only resume once the main thread, blocked in
that wait, ran the hub again. Ctrl-C did not end it; only SIGTERM or
SIGKILL did. The callback gate now counts the main thread's callbacks
apart, and the drain skips them when the main thread itself drains:
only a suspended greenlet can hold one then. A drain on another
thread still waits for them.
- A gevent.Timeout or the GreenletExit of kill() thrown into a greenlet
inside its provider is not an Exception, so it is parked like a
signal, and it was raised in whichever greenlet ran next: another
greenlet failed with B's Timeout, B never saw it, and a killed B ran
on. A parked exception now records its greenlet and is raised only
there; one whose greenlet died is dropped.
- While one greenlet waited in a provider, every other greenlet counted
as inside a token callback, so its QuestDB.close() or lease wait gave
up after two seconds ("cannot wait ... inside a token-provider
callback"). Such waits are now bounded only in the greenlet that is
inside the callback.
The main thread's regions where a parked exception must not be raised
-- token callbacks, diagnostic dispatches, dataframe serialization --
are tracked per greenlet. Without greenlets, or for a region entered
before greenlet was imported, they count for the whole thread as
before, and the main greenlet keeps the existing delivery order. On
PyPy, whose greenlet module is Python code, greenlets are not told
apart.
The docs and changelog say that exit does not wait for a greenlet
suspended in a provider call, so its flush never finishes.
Tests: the three TokenProviderGreenletTest tests, which run gevent in a
child interpreter and skip without it, fail without the fix: the exit
and close() children time out, and A raises B's Timeout.
…esh fixes Pins questdb/c-questdb-client#228 at 6df7aa67, which: - refuses a symlinked OIDC token store however its path is spelled. A trailing separator (`FileTokenStore('<dir>/link/')`, or the same in QUESTDB_CLIENT_OIDC_TOKEN_STORE_DIR) passed the symlinked-leaf check, and a sign-in then chmodded and wrote the link's target; - refuses every spelling of the local machine as a browser sign-in target from a remote identity provider: `127.1`, `2130706433`, `0x7f.0.0.1`, IPv4-mapped loopback, unspecified addresses and `*.localhost` got past the loopback refusal; - returns from a RefreshingTokenProvider's forced refresh at once when failure backoff lets no fetch start before forced_wait ends. Every ILP/HTTP flush answered 401 while the provider backed off stalled forced_wait (5 s) before failing with the same 401. The on_rejected() docstring says so; - passes on a C++ provider's escaping line_sender_error unchanged, and links the OIDC headers from the C and C++ guides. Neither affects this binding.
Two application-provider failures that no retry can fix were reported to native as retryable: - A token() that returns something other than a str (bytes from base64.b64encode() or response.content, None) or a str that is not valid Unicode (a lone surrogate from a surrogateescape-decoded file or environment variable). The binding refuses it before native sees it, and reported a retryable failure, so a connect the caller waits for and QuestDB.dataframe() called the provider until the reconnect budget ran out -- five minutes by default -- while an empty or non-printable token already failed at once. It is now reported as permanent: those calls and an ILP/HTTP flush end at once. Background reconnects keep retrying, as for any classification. The message names the type or the position, never the token. - A closed OidcDeviceAuth reached through a provider of one's own, bearer_token_provider=lambda: auth.token(). Its OidcCancelledError was retried for good: a QWP/WebSocket sender kept reconnecting and reporting CredentialUnavailable with SocketError, and an ILP/HTTP flush used up retry_timeout. The error is now marked as a closed RefreshingTokenProvider's is, so closing the auth ends the provider's clients, reported as ConfigError, as with lambda: tokens.token(). Tests: test_a_token_that_is_no_str_fails_at_once_without_leaking_it, test_closing_an_oidc_auth_a_provider_calls_ends_its_clients and the new cases of test_an_unusable_token_does_not_spin_dataframe_retries fail without the fix.
The token-provider and OIDC callbacks park a Python signal handler's exception for the caller, so a Ctrl-C or a SIGALRM deadline that lands in one still interrupts the flush or sign-in that ran it. Three windows lost it instead: - Classifying an application provider's failure runs Python: the signal-handler test calls into the `signal` module, and the failure's text runs its __str__. A handler that raised there was swallowed with the failure, which was reported as "the token callback failed". On the on_rejected() path it escaped the noexcept callback and was printed as unraisable. The snapshot of installed handlers taken before the call, Python too, had the same gap. - A second interruption during sign_in() -- two signals together, or the first one's queued sibling raised by its pending call -- was dropped when it arrived while a SUCCESS or FAILURE event was rendered: the provider keeps one interrupt to raise. The token callbacks now park an exception raised while they examine a failure, as the OIDC dispatchers already did, and the event path queues a second interrupt for the main thread. sign_in() raises the first and the second surfaces at its native-return boundary, chained to it. Tests: test_a_signal_while_a_provider_failure_is_classified_reaches_the_caller and test_a_second_interrupt_at_sign_in_success_is_not_lost fail without the fix.
A provider may own the client it is attached to: an object that implements token() and keeps its own QuestDB or Sender. CPython collects such an object together with its unclosed client, and so does PyPy, since the client keeps the provider in its instance dictionary. On PyPy that stops holding once the object also holds an unclosed lease or QueryResult of that client: a lease or cursor holds the client and its reader in typed fields, which PyPy's collector cannot see, so the object, the client and its connections stay alive until the process exits. Moving those references where PyPy sees them is not a fix: a value set through the generic attribute protocol lives in PyPy's own instance dictionary, which __dealloc__ cannot read, and every lease and cursor release path needs it there. The token-provider guide now says to close such leases and results, as the API docs already ask, and the reader handle's comment no longer claims cycles through it are collectable everywhere.
The docstring told every caller to sign in first, and said a connection made before any token was acquired raises OidcInteractionRequired rather than blocking the pool. That holds for an OidcDeviceAuth only. The function also takes a RefreshingTokenProvider, which has no sign_in(), and whose token() waits up to cold_wait for a token and then raises TokenUnavailableError, and any other provider, which behaves as its own token() does.
…r code Classifying a bearer_token_provider's failure formats it, which runs the exception's __str__. On the main thread, any exception raised while the failure was classified was parked as if a signal handler had raised it. A failure whose __str__ itself raises -- a provider's own error type that reads a response an unreachable identity provider never sent -- interrupted nothing, yet the flush then failed with "the token callback was interrupted", and the __str__ error was raised again on the main thread once the flush's error had been caught: inside the caller's `except QuestDBError` block, in a context manager's __exit__, at threading shutdown. One for every token request the flush made -- 16 with the default retry_timeout -- and a SystemError at interpreter exit. Such an exception is now parked only when it is no Exception, such as KeyboardInterrupt, or the signal-handler test attributes it to a handler, using the handler snapshot taken before the provider ran; anything else is reported as "the token callback failed", as on any other thread. on_rejected() errors use the same test. A deadline that a signal handler raises while a failure is classified still reaches the caller. Tests: test_an_unprintable_provider_failure_stays_in_its_call fails without the fix, with pending calls queued and with the native-return fallback; test_a_signal_while_a_provider_failure_is_classified_reaches_the_caller still passes.
An application bearer_token_provider stops its clients' background
reconnects by raising its own QuestDBError with code InvalidApiCall. A
TokenUnavailableError is a QuestDBError, and its public `code=` accepts
InvalidApiCall, but clients classify one by `retryable` alone and keep
reconnecting -- deliberately, as native keeps a token-unavailable error
apart from InvalidApiCall. The CHANGELOG ("except QuestDBError with code
set to QuestDBErrorCode.InvalidApiCall that an application provider
raises itself, which stops them") and token_providers.rst ("Only an
InvalidApiCall your provider raises itself has that effect") read as if
it stopped them, so a provider that raised
TokenUnavailableError(..., code=InvalidApiCall) got endless reconnects
and CredentialUnavailable events with cause SocketError instead of a
ConfigError.
The CHANGELOG, token_providers.rst and the TokenUnavailableError,
BearerTokenProvider and ConnectionEventKind docstrings now say to raise
a plain QuestDBError, and that a TokenUnavailableError's code only
labels it. Behaviour is unchanged.
The c-questdb-client pin brings in questdb/c-questdb-client#208, so request_durable_ack now also accepts local, replicated and local,replicated, and sends them to the server. The configuration reference still listed only 'on' and 'off', described for Enterprise object storage, and the 6.1.0 CHANGELOG did not mention the new values, which the previous release rejected. docs/conf.rst now lists every value, what each acknowledgement means and which servers grant it: local needs cairo.commit.mode=adaptive, which QuestDB 10.1.0, Enterprise 4.1.0 and earlier lack; replicated is on's new name, Enterprise only, and Enterprise 4.1.0 and earlier know only on. It also says that the store-and-forward queue keeps a frame until its durable acknowledgement, while this client's acknowledgement waits -- PooledSender.wait(), flush(wait=True), await_acked_fsn() -- wait for the ordinary OK acknowledgement. The CHANGELOG gains an entry.
Pins questdb/c-questdb-client#228 at 2a443686, which: - counts every non-spacing mark against the display sanitizer's cap of four marks on one base character. A combining mark outside its list of stacking blocks ended the run, so interleaving one between listed marks kept a whole "Zalgo" stack in an identity provider's error text. This binding's own renderers and OidcError messages already applied the full cap; a custom Renderer's on_failure() received the native text; - documents that closing a token provider does not wait for a fetch already running. Python's RefreshingTokenProvider.close(wait=True) already offers that wait.
test_interrupt_in_persistence_diagnostic_reaches_token failed on the linux_arm64_manylinux_a release leg (cp312) with OidcNetworkError "Failed to reach .../token: timeout: global". Before it sends a refresh, native tombstones the stored parent token: it takes the store lock, unlinks the entry and fsyncs the directory. That time counts against the request's timeout, and the test inherits the helper's 5 s. A plain OidcNetworkError, not OidcInteractionRequired, means the request was never sent, so the agent spent all 5 s on that local work. Stalling directory fsyncs for 6 s reproduces the same error locally. With the library's 30 s default, the test passes.
|
Reviewing PR #165 at level 3, head cd29d4f, base 8190c2a. Verdict: approve. There are no Critical or Moderate findings, only one optional Minor about an error message. CriticalNone. ModerateNone. Minor1. The refusal for an
How it happens:
Suggested fix: in Adjacent findingsNone new. Coverage mapThe test gate passes, with 0 admitted coverage gaps. The new behaviour has tests that run on every CI leg and in every wheel build: the buffer and sender guards, cursor re-entry and finalizer reclaim, retry slicing, the attribute guard, and the callback and token paths. The one live OIDC round trip ( Summary
The review was read-only: builds and probes ran in scratch worktrees, and the PR's base/head pair was revalidated before posting. |
|
Reviewing PR #165 at level 3, head cd29d4f, base 8190c2a. Reviewing PR #228 at level 3, head 99dd41a38972b2dd2b58b16fa73f3413e1a225d4, base a6fd07f153e9cdeffc5959e738a4de69add7789c. This is a tandem review of #165 and questdb/c-questdb-client#228. Each PR was reviewed with its own repository's review skill. Verdict: approve both. #165 has one optional Minor; #228 has no findings. Both PRs were unchanged at the end of the review. #165CriticalNone. ModerateNone. Minor1. An exception raised by a provider's
How it happens:
The documented behaviour of the other callbacks:
Suggested fix:
Adjacent findingsNothing new. #172 ( Coverage mapThe test gate passes with 0 admitted coverage gaps. The new guards and the provider and OIDC paths are covered by mock-only tests that run on every CI leg and in the wheel builds, for example Summary
questdb/c-questdb-client#228Critical / Moderate / MinorNone. Adjacent findingsNothing new. #231 and #232 are already tracked. Coverage mapThe test gate passes with 0 admitted coverage gaps. Summary
The review was read-only: builds and probes ran in scratch worktrees, and both PRs' base/head pairs were revalidated before posting. |
jovfer
left a comment
There was a problem hiding this comment.
review approve seems valid, please double-check if we should really mark this PR as "breaking changes"
## Summary - Document OIDC device-flow sign-in and rotating bearer-token providers for C/C++ and Rust 7.3.0+, and Python 6.1.0+, with language-specific examples. - Cover discovery, issuer pinning, scopes, silent refresh, token persistence, provider ownership, error handling, and shutdown. Include Python notebook support, managed identities, and PGWire adapters. - Replace obsolete unsupported-authentication claims and align the shared OIDC, connection-string, and QWP behavior references with the new provider and reconnect behavior. - Update connection-setup guidance to reflect eager pool initialization and where authentication failures surface. Related implementation PRs: questdb/c-questdb-client#228 and questdb/py-questdb-client#165.
Summary
Adds OIDC device-flow sign-in and rotating bearer-token authentication to the Python client. Interactive applications, including remote Jupyter notebooks, can sign in through a browser; unattended applications can supply credentials from Azure Identity, an OAuth2 client-credentials flow, or a secrets vault without rebuilding clients whenever a token rotates.
The new
questdb.authAPI uses the native client's authentication, caching, refresh and coordination logic, with Python renderers, token-source callbacks and PG-wire adapters.What this adds
OidcDeviceAuthimplements the OAuth 2.0 Device Authorization Grant (RFC 8628), with configuration discovered from QuestDB or supplied explicitly. It supports terminal and Jupyter prompts, optional QR codes, custom renderers, silent refresh and typedOidcErrorexceptions.RefreshingTokenProviderwraps an application-defined token source with a shared native cache, proactive background refresh, bounded cold waits, refresh hints and backoff. Sources can returnExpiringToken, a(token, expires_at)tuple, or an SDK token withtokenandexpires_onattributes.await_ready()andstatusexpose readiness and fetch diagnostics without exposing credentials.token()and optionalon_rejected(). Shared providers coordinate acquisition across clients; eligible HTTP 401 responses can trigger a refresh and one retry with a replacement token.oidc_auth=andbearer_token_provider=toquestdb.connect,QuestDB.from_conf,Sender,Sender.from_confandSender.from_env. Providers work with HTTP(S) and QWP/WebSocket, not TCP or UDP. They are mutually exclusive with each other and with fixedtoken,usernameorpasswordcredentials.sqlalchemy_enginesupplies the current token as the_ssopassword for each new physical connection;psycopg_connectsupplies it at connection time. Both accept OIDC and application token providers.OidcErrorsubclasses andTokenUnavailableErrorremain catchable asQuestDBError. The additiveConnectionEventKind.CredentialUnavailabledistinguishes failure to obtain a credential from a server rejecting one (AuthFailed); existing event ordinals are unchanged.Interactive sign-in
Rotating machine credentials
Wrap an application-defined
fetch_token()returning a token and its expiry:The token-provider guide includes Azure Identity and OAuth2 client-credentials recipes. Cloud SDKs remain application dependencies; OIDC itself adds no mandatory Python dependency. SQLAlchemy, psycopg, IPython and QR support are loaded only when needed.
Lifecycle and security
sign_in()is interactive. Token reads, transport reconnects and PG pool connections never launch a sign-in prompt.Ctrl-Candcancel_sign_in()cancel an active attempt without retiring the provider;close()permanently closes it and terminates its attached clients' token acquisition.TokenUnavailableError.retryablecontrols foreground retry decisions; even a permanent token-unavailable failure does not stop background reconnects. To end them, close the provider, or have an application provider deliberately raise a plainQuestDBErrorwithInvalidApiCall.FileTokenStorestores plaintext credentials using atomic replacement and cross-process refresh coordination. Writes currently require POSIX storage with enforceable owner-only permissions; use in-memory authentication on other platforms. Discovery endpoints, browser targets, display text and credential diagnostics are validated or sanitized before use.https::orwss::; plaintext transports warn rather than reject the configuration. PG adapters default toverify-fullfor remote hosts and reject destination or login overrides that could redirect the token. Numeric loopback addresses retain a local-development fallback.RefreshingTokenProvider.close(wait=True, timeout=...)can drain an active fetch. Callback admission, shutdown draining, signal delivery and greenlet isolation protect the Python/native boundary. Providers and clients must not be carried acrossfork().Compatibility notes
These affect existing APIs and are documented in the
6.1.0 (unreleased)changelog:AuthFailedwith capped backoff instead of becoming terminal. This also applies to fixed credentials. A waited-for initial connection still fails on rejection. Applications that want to stop an established sender must close it from their own code, outside its listener.flush()/close()restrictions extend torow(),dataframe(),new_buffer(),establish()and transaction operations. Several native-backed getters also reject access during a native call. These refusals raiseQuestDBError(InvalidApiCall); queue callback work or use another sender.InvalidApiCallduring a modifying flush or row-serializing DataFrame operation. A kept flush (clear=False) remains a read-only borrow and permits other readers.PooledReader.close(), raiseInvalidApiCall. Close after the read returns or from another thread.token_provider,azure_resource,azure_client_idandazure_credentialfrom configuration strings and pass the provider as a Python keyword argument instead.Sendersubclasses see its attribute guard and instance dictionary. Usesuper().__setattr__rather thanobject.__setattr__on CPython 3.10–3.12, place attribute-hook mixins beforeSender, and do not rely on subclass__slots__to prevent new attributes.Supporting changes
examples/oidc_device_auth.py.request_durable_acklevels (local,replicated,local,replicated, pluson/off), server compatibility and the distinction between durable retention and ordinary acknowledgement waits.Testing
Regression coverage includes device polling and refresh failures, credential-safe rendering, token-store permissions and concurrent refresh, cancellation and signals, provider sharing and shutdown, HTTP/WebSocket authentication, query failover, callback re-entry, garbage collection and real PG-driver handshakes. Dedicated OIDC, PG capture and QWP failover servers exercise these paths locally. Provider entry points also have mypy coverage.
At head
cd29d4f, all 31 reported checks pass, including:master.Native dependency
The
c-questdb-clientsubmodule is pinned to2a443686from questdb/c-questdb-client#228. Update the pin to the merged nativemaincommit before merging this PR.