Skip to content

fix(qwp)!: bound inputs and harden HTTP, failover, and shutdown - #226

Closed
glasstiger wants to merge 3 commits into
mainfrom
ia_oidc_extracted_fixes
Closed

glasstiger wants to merge 3 commits into
mainfrom
ia_oidc_extracted_fixes

Conversation

@glasstiger

@glasstiger glasstiger commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

1. Stricter input validation — breaking changes

  • Caps caller-supplied C connection/config strings at 1 MiB, exposed as QUESTDB_CONFIG_MAX_BYTES.
  • Rejects oversized strings before reading their memory; validates UTF-8 and rejects NULL pointers with non-zero lengths. Environment-based constructors remain uncapped.
  • Caps connection-event and rejection callback inboxes at 65,536 entries, preventing unreasonable allocations from aborting the process.
  • Oversized capacities produce ConfigError in Rust/sender configuration and InvalidApiCall in the C pool APIs.

2. More informative query-failover errors

In questdb-rs/src/egress/reader.rs:

  • Rechecks the wall-clock deadline immediately after a failed reconnect round.
  • Preserves a final RoleMismatch, HandshakeError, or TlsError, rather than obscuring it with a generic transport error when the deadline expires.
  • Retains the original failure when no reconnect produced a more useful diagnosis.
  • Adds regression tests and updates the C/C++ documentation for these semantics.

3. HTTP/HTTPS fixes

  • Explicitly ignores HTTP_PROXY, HTTPS_PROXY, and ALL_PROXY: the existing connector does not support proxies, but previously picked up those settings and could fail every flush with “Connection refused.”
  • Fixes HTTPS certificate verification for IPv6-literal hosts such as [::1].
  • Rejects an unrepresentable retry_timeout with a configuration error instead of panicking.

4. Background-worker and Windows shutdown hardening

In questdb-rs/src/ingress/sender/qwp_ws.rs:

  • Catches background-worker panics in unwind-enabled builds, marks the publication state terminal, and wakes producers blocked on backpressure.
  • Cancels Windows runners blocked in synchronous TLS/WebSocket setup during shutdown.
  • Synchronizes cancellation with the setup state so it cannot accidentally interrupt store-and-forward disk writes.

5. Arrow ingestion optimization

For FixedSizeBinary columns without an explicit QuestDB type:

  • Uses the actual element width for frame-size estimation instead of assuming 16 bytes per row.
  • Adds a bulk encoding path for columns without nulls, avoiding per-row payload copying.
  • Adds encoding and size-estimation tests.

6. Tests, documentation, and infrastructure

  • Adds input-boundary, C-header/Rust constant consistency, dispatcher shutdown, retry-classification, and failover tests.
  • Improves flaky background-send and orphan-worker tests.
  • Fixes the Windows console-control helper used by system tests.
  • Gives test cleanup DROP TABLE calls a 30-second timeout, without retrying potentially applied DDL.
  • Corrects enterprise-test handling of post-DROP ACL cleanup errors and orphan-drainer shutdown ordering.
  • Clarifies UUID byte order and C pointer-argument requirements.

…wn paths

Changes extracted from the OIDC / rotating bearer token PR (#183) that do
not depend on either feature, so that PR can shrink to the feature itself.

Breaking:
- Config strings longer than QUESTDB_CONFIG_MAX_BYTES (1 MiB) are rejected
  by every C entry point that takes a caller-supplied string
  (line_sender_opts_from_conf, line_sender_from_conf, questdb_db_connect*,
  qwp_direct_sender_from_conf, qwp_reader_from_conf), before a slice is
  formed. The *_from_env family stays uncapped.
- Callback inbox capacities are capped at 65536: connection_listener,
  the error_inbox_capacity conf key (ConfigError) and the C pool entry
  points (InvalidApiCall, QUESTDB_DB_MAX_CALLBACK_INBOX_CAPACITY). The
  capacity reaches VecDeque::with_capacity, which aborts the process on
  allocation failure.
- A query failover that runs out of failover_max_duration_ms while
  attempts remain keeps a RoleMismatch / HandshakeError / TlsError found
  by the last round instead of reporting the transport error that started
  the failover; the deadline is re-checked right after a failed walk.
- A durable-ACK store-and-forward pool retries an all-replica role reject
  until the borrow budget expires, as a direct sender already did.

Fixes:
- ILP/HTTP ignores HTTP(S)_PROXY / ALL_PROXY instead of failing every
  flush with "Connection refused".
- HTTPS to an IPv6-literal host verifies against the IP address instead
  of failing before the handshake.
- An unrepresentable retry_timeout is a ConfigError, not a panic.
- An ACK wait or manual close that times out while reconnecting keeps
  failing names that failure; manual close_drain honours its deadline
  while a reconnect is waiting instead of spinning.
- A panicking background worker terminalizes the publication store and
  wakes backpressured publishers.
- Windows: shut down the original traffic socket before CancelIoEx, and
  cancel a runner blocked in TLS/WebSocket setup on shutdown.
- Unlabeled FixedSizeBinary: exact frame-size estimate and a bulk path for
  dense columns.
- Error::reclassified keeps every structured diagnostic when an error is
  re-coded or annotated.
- Doc fixes: UUID byte order of qwp_reader_column_data, pointer-argument
  convention in client.h.

Tests and CI: provider-free tests for the above, flaky test fixes, run
the questdb-rs tests with ffi-support, system_test cleanup and e2e
fixes, bump the questdb submodule.
@coderabbitai

coderabbitai Bot commented Oct 19, 2026 •

Copy link
Copy Markdown

Important

Draft PR not reviewed

Draft PRs are not automatically reviewed by default.

  • Trigger a manual review

To automatically review draft PRs, update your CodeRabbit configuration:

reviews:
  auto_review:
    drafts: true
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

glasstiger added a commit that referenced this pull request Oct 19, 2026
Stack this PR on #226, which carries the changes extracted from it that
do not depend on OIDC or token providers. The extracted code now matches
#226 exactly; what remains in this PR's diff against #226 is the feature
and the spec-driven changes #226 leaves here on purpose.

Conflicts: took #226's version of the extracted code plus this PR's
feature additions (questdb_db_connect_ex, OIDC payloads, provider paths).
Kept #226's provider-free tests next to the provider-based variants,
which are renamed where both used the same name:
- qwp_ws_manual_close_honors_deadline_while_token_refresh_fails
- qwp_ws_wait_forgets_a_credential_failure_once_reconnected
Dropped the copies of tests and of QUESTDB_DB_MAX_CALLBACK_INBOX_CAPACITY
that the merge placed twice.

Drop this PR's enterprise_e2e/conftest.py JAVA_TOOL_OPTIONS temp dir
fix in favour of the JAVA_OPTS_FORK one main already has (#215).
glasstiger added a commit to questdb/py-questdb-client that referenced this pull request Oct 19, 2026
Stack this PR on #160, which carries the changes extracted from it that
do not depend on OIDC, token providers or #140. The extracted code now
matches #160; what remains in this PR's diff against #160 is the feature,
#140's UUID / fixed-size-binary work, and what #160 leaves here because it
needs the newer native client (the config-string and callback-inbox caps,
CredentialUnavailable, the native fixes reaching Python through the pin).

Conflicts: took #160's version of the extracted code and wording, plus
this PR's OIDC additions. Changelog and migration guide: #160's entries
in #160's order, with this PR's own entries around them; dropped this
PR's copies of the cursor re-entry and close-retry bullets that #160 now
carries.

Bump c-questdb-client to the head of questdb/c-questdb-client#183, now
stacked on questdb/c-questdb-client#226.
qwp_ws_manual_close_honors_deadline_while_reconnect_is_waiting,
qwp_ws_wait_names_a_failing_initial_connect and
qwp_ws_wait_names_a_failing_background_reconnect pointed reconnects at a
closed port. Windows retransmits the SYN against a refused loopback port
for about 2 s before failing the connect, longer than the 500/800 ms
waits and the 2 s close bound, so all three failed on both Windows
images.

Drop connections at accept instead, as spawn_accept_then_drop_server
already does for the same reason: every reconnect then fails fast at the
WebSocket upgrade on every platform.
glasstiger added a commit that referenced this pull request Oct 21, 2026
OIDC device-flow sign-in (RFC 8628) and rotating Bearer-token providers
for the Rust, C and C++ clients, split out of #183 so the feature can be
reviewed against `main` without the unrelated fixes of #226.

Besides the feature, this carries the few pieces of #226 the feature
depends on:

- `Error::reclassified`, which keeps OIDC and token-provider diagnostics
  when an error is re-coded or annotated (reader endpoint errors,
  retry-budget and failover-deadline exhaustion).
- ACK waits and the manual-progress close drain name the failure when
  they time out while reconnecting keeps failing, so a credential that
  needs a new sign-in reads as INTERACTION_REQUIRED. A manual close drain
  also stops at its deadline while a token refresh keeps failing.
- `server_name_for_uri_host`, used by the OIDC HTTP client for IPv6
  literal IdP hosts.
- The store-and-forward pool's connect error keeps its payload, so an
  OIDC failure stays typed. The kept role-reject payload also lets a
  durable-ACK pool retry an all-replica role reject until the borrow
  budget.

The full history is on branch `ia_oidc_device_flow` (#183).
glasstiger added a commit that referenced this pull request Nov 12, 2026
* feat(oidc)!: add OIDC and rotating bearer tokens

OIDC device-flow sign-in (RFC 8628) and rotating Bearer-token providers
for the Rust, C and C++ clients, split out of #183 so the feature can be
reviewed against `main` without the unrelated fixes of #226.

Besides the feature, this carries the few pieces of #226 the feature
depends on:

- `Error::reclassified`, which keeps OIDC and token-provider diagnostics
  when an error is re-coded or annotated (reader endpoint errors,
  retry-budget and failover-deadline exhaustion).
- ACK waits and the manual-progress close drain name the failure when
  they time out while reconnecting keeps failing, so a credential that
  needs a new sign-in reads as INTERACTION_REQUIRED. A manual close drain
  also stops at its deadline while a token refresh keeps failing.
- `server_name_for_uri_host`, used by the OIDC HTTP client for IPv6
  literal IdP hosts.
- The store-and-forward pool's connect error keeps its payload, so an
  OIDC failure stays typed. The kept role-reject payload also lets a
  durable-ACK pool retry an all-replica role reject until the borrow
  budget.

The full history is on branch `ia_oidc_device_flow` (#183).

* fix(oidc): stop a 401 re-fetch from handing back the rejected token

After a server rejects a token with HTTP 401, the connection pulls the
token again with the rejection attached, so the provider can refresh it.
On the shared isolated worker that pull joined whatever fetch was already
in flight. When it joined fetches started by other connections twice in
a row, it took the rejected token back as the provider's answer, although
the provider was never told about the rejection. An async-connect
QWP/WebSocket sender then failed with a 401 it would have recovered from,
and a reader's mid-query failover gave up.

Each isolated fetch now records the rejection its worker passes to the
provider. A re-fetch accepts a result only from a fetch that carried its
own rejection: it waits out any other fetch and then leads one, so a
provider still runs at most one isolated worker at a time. A re-fetch
that told the provider no longer asks it a second time when the provider
answers with the same token.

* fix(qwp): keep terminal rejection diagnostics off ACK-wait timeouts

A manual-progress QWP/WebSocket sender whose reconnect budget ran out
before its first attempt latched the budget error as the reason
reconnecting keeps failing. That error wraps what started the reconnect,
such as a retriable server rejection, so a later ACK-wait timeout carried
the rejected batch's diagnostic. line_sender_error_qwpws_get_view then
returned true for a retryable failover_retry error, although it is
documented to do so only for a terminal diagnostic, and the message
claimed reconnecting kept failing with attempts=0. With
reconnect_max_duration_millis=0 that message also grew with every pass.

A budget that made no attempt no longer latches a reconnect failure, in
both the manual driver and the background runner. ACK-wait and manual
close-drain timeout errors also drop a server-rejection diagnostic from
their cause, while keeping its OIDC, token-provider and role detail.

* fix(oidc): stop a RefreshingTokenProvider deadlock on HTTP 401

A forced refresh logged its "refreshing early" line while it held the
provider's state lock, and `Debug` for the provider takes the same lock.
A thread that formatted the provider while holding a log backend's output
lock -- `eprintln!("{provider:?}")` with a stderr logger -- deadlocked
with the thread handling the 401, and with them every later user of the
provider. The line is now logged after the lock is released, as the
provider's other log lines already were.

A RefreshingTokenProvider wrapped in a closure (`move || p.token()`) or
in a type of the application's own never heard of a 401: the wrapper's
`on_rejected` is the trait's no-op, so the re-resolution got the
rejected token back and every ILP/HTTP flush failed until the scheduled
refresh, about half the token's lifetime later. `token()` now refreshes
early when the calling thread is replacing a token a server rejected
with 401, as a wrapped OidcDeviceAuth already did.

A connected QWP/WebSocket sender rides out credential rejections past a
reconnect budget only because the budget's error keeps the rejection's
HTTP status, and no test crossed a budget expiry. New driver and sender
tests ride out 401s and 403s over several budgets, in both progress
modes, and then deliver the queued row.

The C and C++ token-provider headers said `get_token` runs once per
connect round, on a connect thread or an isolated worker. On an ILP/HTTP
sender it runs on every flush, on the flushing thread; they now say so.

* fix(qwp): name a failing reconnect in flush and close-drain timeouts

A sender that has connected now rides out a server's 401/403 instead of
becoming terminal, so a credential revoked mid-stream no longer fails the
next call with an AuthError. ACK waits and the manual-progress close drain
already named the reconnect failure in their timeout errors. The default
background close drain and a flush that waited out
sf_append_deadline_millis on a full queue did not: they reported a bare
close-drain timeout, and the append timeout advised increasing
sf_max_total_bytes, which cannot help while nothing can be acknowledged.

Both now name the latest reconnect failure, keeping its OIDC and
token-provider detail and dropping the server-rejection diagnostic, as
the ACK-wait timeout does. With no reconnect failure latched, the
messages are unchanged.

* fix(oidc): make the C++ token_provider non-copyable like device_auth

A copy of questdb::token_provider was another handle on one shared
provider, so close() on a copy permanently ended every sender, pool and
reader the original was attached to. oidc::device_auth deletes its copy
operations for exactly that reason and offers share() instead.

token_provider now does the same: the copy operations are deleted, moves
remain, and share() takes an explicit additional handle. The C header
documents that questdb_token_provider_clone aliases the provider rather
than duplicating it.

* chore(oidc): hide the C-ABI-only OidcError constructors from rustdoc

retryable_interaction_required, reentrant_interaction_required,
config_error and closed_error exist so the FFI crate can build typed
OIDC errors. They were rendered as documented public API, while every
other binding-only hook this feature adds is #[doc(hidden)].

* fix(oidc): name only compiled-in APIs in the reserved-key error

The error for a token_provider or azure_* connect-string key pointed
Rust callers at SenderBuilder::bearer_token_provider and
ReaderConfig::token_provider. The first needs both the ILP/HTTP and the
QWP/WebSocket sender, the second the reader, so an oidc-only or
single-transport build was sent to methods it does not have. The
message now names the methods the enabled features compile in.

* feat(oidc): let C and C++ token providers stop background reconnects

A Rust token provider stops the background reconnects of the senders,
readers and pools it serves by returning InvalidApiCall, which is carried
as a terminal ConfigError. A C or C++ application provider had no
equivalent: questdb_token_sink_set_error yields a token-unavailable
error, which background reconnects retry whatever its classification,
and the C++ wrapper reported every exception through that call. A
provider that knew it could never succeed kept its clients reconnecting
until the application closed them.

questdb_token_sink_set_terminal_error reports such a failure from a
get_token callback, carried as InvalidApiCall exactly as from a Rust
provider. A C++ bearer_token_provider throws questdb::error with
invalid_api_call. A refreshing provider's token source cannot report
one, and the sink refuses it: closing the provider is how that kind
stops its clients.

The Rust and C++ docs also said every 401 makes the transport call
on_rejected and resolve the token again. That happens only when the
401's WWW-Authenticate Bearer challenge names no error, or
invalid_token, as the C headers already said; the Rust and C++ docs now
say so too. And the docs of questdb_db_borrow_sender_with_retry and
reconnect_pick still called every protocol-version error terminal,
although a durable-ack pool now retries an all-replica role reject
until the borrow budget runs out.

* update submodule

* fix(oidc): end a waiting connect at once on an invalid provider token

A token provider that returned a blank token, or one with a byte outside
printable ASCII, made a connect the caller waits for pull it again until
reconnect_max_duration ran out: the synchronous initial connect, a
direct-sender pool borrow with retry, and an eager synchronous pool
connect. A token file read with its trailing newline was enough. The
same provider returning an unclassified error ends that connect at once,
as the qwp_ws_token_provider docs promise for every provider failure the
provider did not classify retryable.

The validation error is now marked as a provider failure, like the
provider's own errors, and so is the unwind-only error for a provider
that panicked. Background reconnects still retry both, so queued
store-and-forward frames stay replayable, and ILP/HTTP flushes are
unchanged. A reader whose failover gives up on an invalid token now
reports it rather than the transport error that started the failover,
as for any other provider failure.

* fix(oidc): defang every scheme in a refused sign-in URL

The terminal sign-in prompt shows a verification URL that safe_target
refused as inert text, with its scheme broken so that terminals do not
auto-link it. It broke a scheme only at the very start, although
safe_target vets the stripped and trimmed URL. An identity provider
that put a space, an NBSP or a word before a refused URL (userinfo,
punycode or remote plaintext http) had it printed with a live scheme.

defang_terminal_url now breaks every :// in the refused text. A URL
that starts with its scheme prints as before. The doc comment that
describes format_prompt is back on format_prompt.

* update submodule

* docs(oidc): say waited-for connects end on transient OIDC failures

The OIDC docs named only a missing sign-in as ending a QWP/WebSocket
connect the caller waits for: the synchronous initial connect or a pool
borrow with retry. Such a connect actually ends on every OIDC failure
except a busy acquisition, a transient refresh failure included. An
OidcDeviceAuth classifies none of its failures retryable, so an identity
provider answering 5xx during a silent refresh fails the build or the
borrow after one provider call, whatever its budget. That matches spec
D8 and the Java client. Background reconnects keep retrying, and an
ILP/HTTP flush resolves the token again until its retry_timeout expires.

The docs of line_sender_opts_oidc_auth, questdb_db_connect_ex and both
borrow-with-retry calls, their C++ and Rust counterparts,
OidcErrorKind::Network and SECURITY.md now say so. The
credential_unavailable event docs no longer claim that every initial
connect fails fast: a synchronous one, or a pool borrow with retry,
still retries a failure the provider classified retryable. A new test
pins the Network case at the synchronous initial connect.

* fix(oidc): keep manual close and wait deadlines with a refreshing provider

In manual progress mode a reconnect pulls the token on the thread that
drives progress, inside close_drain, wait or a flush waiting for queue
space. Those calls check their deadlines only between attempts, so a
RefreshingTokenProvider that held no usable token kept them for its
whole cold_wait (30 s by default) while its refresh stalled.

Such a pull no longer waits: it takes the cached token, or fails the
attempt at once while the provider's refresher keeps fetching, and a
later attempt pulls again. A connect the caller waits for, such as the
initial connect, still waits for the provider.

* ci(test): run the questdb-rs tests with ffi-support

The pool's borrow-with-retry paths and their tests compile only with
the ffi-support feature, which no CI leg enabled for the questdb-rs
tests, so the test for retrying a durable-ACK pool's all-replica role
reject never ran in CI. Add the feature to the almost-all-features run;
the arrow/polars run still covers the build without it.

* fix(oidc): name the cause of a refused sign-in token response

When the device-code poll got HTTP 200 but the token response then
failed validation, the sign-in failure line always read "the identity
provider returned an unsupported token type". A negative or non-numeric
expires_in, or a refresh token this client cannot store, is refused
there too, and sign_in() already returned an error naming that cause.
The terminal prompt and the C QUESTDB_OIDC_EVENT_FAILURE event now show
the returned error's message.

* fix(oidc): handle a non-UTF-8 provider token like any invalid token

questdb_token_sink_set_token refused a token that is not valid UTF-8 and
recorded nothing. The C++ wrappers ignore its result, so a C++ provider
or token source that returned such a token -- read from a UTF-16 file,
say -- failed as having "reported neither a token nor an error",
classified retryable. A connect the caller waits for, such as the
synchronous initial connect, then pulled the provider until
reconnect_max_duration ran out, although an invalid token from a Rust
provider ends it at once.

The sink now records the refused token as the callback's failure, naming
it, and leaves it unclassified, as a token with any other byte outside
printable ASCII is: a waited-for connect ends at once, background
reconnects retry it, and a refreshing provider's source counts it as a
retryable fetch failure. questdb_token_sink_set_token still returns
false for it, and questdb_token_provider_token now reports it too.

* fix(oidc): leave user_data with the caller when a provider is refused

The C callback registrations disagreed on who owns user_data after a
failed call. The OIDC event and diagnostic handlers leave it with the
caller, as questdb_db_connect_with_event_handler always has, while
questdb_refreshing_token_provider_new and questdb_token_provider_new ran
release on it. A binding that frees user_data after a NULL return, as
the OIDC header documents, would free it twice, and one that follows the
token provider rule would leak an OIDC handler's.

Both constructors now follow the OIDC rule: a failed call leaves
user_data with the caller and does not run release, also when the
refreshing provider's own build refuses its options. The C++
token_provider factories keep their copy of the source or provider until
the call succeeds, and both headers state the rule and point at each
other. The Python binding's release callbacks do nothing, so it is
unaffected.

* fix(oidc): reject in-callback waits at once and version provider structs

A store-and-forward wait made inside an OIDC auth callback is rejected
once the sender's reconnect needs a token that the callback withholds.
When the callback began only after the runner had started its isolated
token pull, the worker's refusal reached the runner without marking that
attachment as blocked, so the wait stayed parked until the next
reconnect attempt, up to reconnect_max_backoff later. The runner now
resolves such a refusal again on its own thread, as it already did when
it saw the callback first.

The four size-prefixed token-provider C structs took their current size
as the minimum struct_size, and the provider and options inputs were
read whole, so appending a field would have rejected every caller built
against this header, or read past its struct. The minimums are now
pinned to the first published layouts, the inputs are read field by
field up to struct_size with defaults beyond it, as
questdb_db_connect_options already is, and frozen-v1 tests guard the
layouts. questdb_refreshing_token_provider_options_init now records the
caller's allocation size in struct_size, as the header states, rather
than the smaller of it and the library's size.

The C++ token_provider gains status(), the refreshing provider's state
that C reads with questdb_token_provider_get_status and Rust with
RefreshingTokenProvider::status. Its times saturate to the clock's
range: a token that never expires is reported as expiring in 9999,
which a nanosecond system_clock cannot hold.

* docs(oidc): say when an HTTP flush calls the token provider again

The ingress guide said an ILP/HTTP sender resolves its token once per
flush and reuses it for every retry request in that flush, so a provider
with side effects could expect exactly one call. A flush calls it again
in two cases: after a provider failure that can clear on its own, with
backoff until retry_timeout expires, and after an HTTP 401 whose Bearer
challenge allows a refresh, when it replays the request once if the
token changed.

The guide now says the provider normally runs once per flush and names
both cases. The oidc module example and the oidc_device_auth example
said it resolves again only after a 401; they now name both cases too.

* fix(oidc): stop the clients of a C++ provider passing on a closed one

A C++ bearer_token_provider whose token() let the error of a closed
refreshing token_provider escape had it reported to the sink as
retryable. The senders, readers and pools using it then kept
reconnecting for good, where the provider attached as is, a Rust
closure returning the same error, and the Python binding all stop
them: closing a provider ends every client that uses it, as its C and
C++ docs state. The glue also dropped the classification such an error
carries, so a permanent failure was re-reported as retryable without
its retry-after, and a connect the caller waits for retried it until
its budget ran out instead of ending at once.

The C++ glue now reports the failure of a closed provider, and an
oidc::error of kind cancelled or config, as terminal, as a Rust
provider returning them is classified, and forwards any other
classification the error carries. questdb_token_unavailable_view gains
provider_closed, appended after the first layout, so C and C++ can
tell a closed provider's failure from a permanent one;
TokenUnavailable::provider_closed is public in Rust to match.

* fix(qwp): name no background runner in a manual sender's wait timeout

An ACK wait that timed out on a sender built with
qwp_ws_progress=manual said that the background runner keeps
delivering the frames, or keeps reconnecting while the connection is
down. A manual-progress sender has no runner: it delivers and
reconnects only while its caller drives it with drive_once(), wait(),
flush() or close_drain(). The message now says so, and points at
close_drain() rather than at closing a pool. Background senders and the
store-and-forward wait keep their wording.

* fix(oidc): pass a delegated OIDC failure on unchanged and wipe the refreshing token cache

A C++ bearer_token_provider that calls oidc::device_auth::token() and lets
the oidc::error escape had it re-reported through
questdb_token_sink_set_error as a retryable failure without its OIDC
detail. With nobody signed in, a sync initial connect or a pool borrow with
retry then retried for its whole budget (reconnect_max_duration, 300 s by
default), where the same auth attached with opts::oidc_auth, or passed on
by a Rust closure, ends it at once; and the client's error had no
oidc_diagnostic().

Add questdb_token_sink_set_error_from, which passes another QuestDB token
API's error on unchanged: its code, its classification and its OIDC
detail. The C++ adapter uses it for every non-terminal oidc::error the
library raised, which now keeps the C error it was converted from. A closed
or misconfigured auth still stops the clients with config_error.

RefreshingTokenProvider now wipes its cached token when a refresh replaces
it, on close and on drop, as the OIDC token cache is wiped. zeroize comes
with the oidc feature, which the C ABI library always enables.

* docs(oidc): say what set_error_from does from a token source

The docs said a token source could pass on an OIDC failure unchanged
with questdb_token_sink_set_error_from, keeping its classification and
OIDC detail, so that a waited-for connect ends at once. A refreshing
provider instead treats a source's error as a failed fetch, as it does
for a Rust source: an unclassified OIDC failure counts as retryable, a
sync connect retries it for its whole budget, and clients get the
provider's own error without the OIDC detail.

The C, C++ and Rust docs now say so, and name how a source ends a
waited-for connect at once: report the failure as not retryable, or
attach the auth directly. A test covers both a passed-on failure and a
non-retryable one.

* fix(oidc): pass a closed auth's OIDC failure on unchanged in C++

A C++ bearer_token_provider that let the oidc::error of a closed
device_auth (kind cancelled) or of a misconfiguration (kind config)
escape reported it through questdb_token_sink_set_terminal_error. The
clients stopped, but with config_error and without the OIDC detail,
where a Rust provider returning the same OidcError stops them with its
own code (auth_error for cancelled) and keeps the detail.

The adapter now passes every oidc::error the library raised on with
questdb_token_sink_set_error_from, which the client classifies as it
classifies a Rust provider's error: these two kinds still stop it. An
oidc::error constructed in C++, which has no C error to pass on, keeps
the terminal report.

* fix(oidc): pass a closed token provider's failure on unchanged in C++

A C++ bearer_token_provider that let the questdb::error of a closed
refreshing token_provider escape reported it through
questdb_token_sink_set_terminal_error. The clients stopped, but with
config_error and without the token-unavailable classification, so
provider_closed was lost. A Rust provider returning the same error
stops them with auth_error and keeps provider_closed set.

Every questdb::error converted from a C error now keeps that error, as
oidc::error already did, and the adapter passes one that carries a
classification on with questdb_token_sink_set_error_from. The client
then classifies it as it classifies a Rust provider's error. A
questdb::error without a classification, or constructed in C++, keeps
the existing report. The provider_closed docs in token_provider.h now
point get_token callbacks at questdb_token_sink_set_error_from.

* fix(oidc): tell an unanswered token endpoint from an unreachable one

When every device-flow poll failed without an HTTP response until the
device code expired, the prompt said the token endpoint was never
reachable. It said so too for a token endpoint that accepted each poll
and then dropped it or never answered, which sent the user looking for
a network or DNS problem.

The poll loop now records whether any poll was sent or got an HTTP
response. If one was, the expiry says the token endpoint did not
respond; if none was, it still says it was never reachable. The error
class, the expired_token tag and the start of the message are
unchanged.

* fix(oidc): box the ILP/HTTP sender's token provider

HttpAuth held its TokenProvider inline. That made the ILP/HTTP variant
of SyncProtocolHandler large enough that plain cargo clippy, with the
default features, reported large_enum_variant against it.

The provider is now boxed, so HttpAuth is again as small as a String,
and a sender with static credentials or none keeps the same state
layout it had before token providers. Boxing the whole HTTP state
instead would have moved the warning to the builds with QWP/UDP, where
that variant then becomes the outlier.

* docs(oidc): say when a non-retryable source failure ends a connect

The questdb_token_sink_set_error_from docs said a token source ends a
connect the caller waits for at once by reporting its failure with
questdb_token_sink_set_error as not retryable. The connect does not
retry that failure, but the refreshing provider's cold wait comes
first: the provider retries a failed fetch whatever its classification,
and the pull keeps waiting while the next retry is due within
cold_wait. With the default options that can take up to 30 s. Only a
backoff that outlasts cold_wait ends the wait at once, and that was the
only case the test ran.

The wait itself follows spec §5.3, which ends it only with a usable
token, when cold_wait elapses or on cancellation, and §5.4, which keeps
retrying a "permanent" failure because an operator can repair it
without a restart. The Java client waits the same way. So the behaviour
stays, and the header now says such a failure ends the connect when
the provider's cold wait does. Attaching the auth directly still ends
it at once.

The FFI test now also runs the non-retryable case with a backoff within
the cold wait. A new provider test checks that a permanent failure
whose retry falls within cold_wait does not end the wait.

* fix(oidc): keep a lagging host's live store lock from being taken

The token store's directory lock has a two-second lease, which a holder
renews by writing its own clock into the lock's mtime. A contender aged
that mtime against its own clock, so a holder on another host whose
clock was more than two seconds behind lost the lock to the first
contender while still renewing on schedule. Its load, save or clear then
failed with "lost ownership of the OIDC token-store directory lock", and
a failed save after a refresh left the rotated refresh token
unpersisted.

The wall-clock age now decides only for a holder whose stamp names this
host. Any other holder -- on another host, or a Java holder, whose stamp
names none -- loses the lock once the contender has itself watched it go
unrenewed for the lease, on its own monotonic clock, or once the lock is
older than the five-minute minimum stale window. A waiting contender
still reclaims the lock of a holder that crashed elsewhere after about
two seconds. The per-identity lock, whose lease is at least five
minutes, is unaffected.

* docs(db): say where a pooled reader gets its configuration

QuestDb::borrow_reader said a new pooled reader connection opens with
Reader::from_conf on the original connect string. Pooled readers open
from the reader configuration parsed when the pool opened, which carries
a token provider attached with connect_with_token_provider. The connect
string is parsed again only to report the error of one whose query-side
settings were rejected.

* fix(oidc): support nested request dispatch hooks

* fix(oidc): keep a refresh token a slow token store delayed past its deadline

A durable refresh clears the persisted parent from its token store just
before the refresh request's first byte goes out. The transport checked
the request deadline only before that callback, so a clear() that
returned after the deadline -- a custom store waiting on a vault or
running a nested refresh, or a file store whose lock a frozen or crashed
peer held past a short OIDC timeout -- still had the request head
written and the request marked dispatched. Its body was then refused as
late, and the refresh discarded a parent the identity provider never
received, forcing a new interactive sign-in.

The transport now charges the callback's time to the request. When the
callback used up the deadline, the request fails before any byte is
written, as unsent, and the refresh keeps the parent in memory and in
the store for the next attempt.

A new test makes the first clear() outlast a 300 ms timeout: the refresh
fails retryably with the parent kept, and the next session refreshes it.

* fix(oidc): report how many status message bytes were copied

questdb_token_provider_get_status truncates the last failure's message
at a character boundary to fit the caller's buffer, so it can copy fewer
than min(last_failure_msg_len, last_failure_msg_capacity) bytes. Nothing
reported how many, so a caller reading that many bytes from a buffer
under 1024 bytes could take up to three stale bytes and an invalid UTF-8
sequence after the message.

The status now ends with last_failure_msg_copied, the number of bytes
copied. The struct is size-versioned: a caller built against the
previous layout keeps receiving exactly that prefix. The C++ wrapper and
the Python binding pass a buffer of at least 1024 bytes, which always
fits the message, so they are unaffected.

* fix(auth): free native tokens when C++ copying throws

Own the returned native token before constructing its C++ string so exceptions also free and zeroize it.

Add a deterministic string-copy exception regression test and run it through the C++17/C++20 test matrix.

* fix(oidc): charge renderer callbacks to device-code expiry

* test(qwp): synchronize standalone sender drop assertions

* test(auth): bound cold-wait test clock driving

* fix(oidc): commit terminal failures before renderer callbacks

Serialize terminal failure commitment with attempt cancellation so a\nrenderer cannot receive an accepted cancellation that sign-in ignores.\nPreserve the original error once the failure callback starts.\n\nCover callback-thread and concurrent cancellation across seven terminal\nfailure paths, retain provider reuse, and document the boundary.

* fix(oidc): accept reissued tokens during explicit sign-in

* fix(auth): keep a refresh at least 1 ms after its fetch

A RefreshingTokenProvider whose min_refresh_interval was zero, or below a
millisecond, scheduled the next fetch at the moment of receipt when the
source's refresh hint was at or before it. While the source kept returning
such a hint -- Azure Identity hands back its cached token with the passed
refresh_on during an IMDS outage -- the refresher thread fetched without
pause: about 10^5 source calls a second, and a CPU core kept busy.

The specification already requires a failure backoff to stay positive after
rounding, with a 1 ms minimum for whole-millisecond implementations (§5.4).
Apply the same minimum to the spacing between a fetch and the refresh that
follows it, so 0 behaves as 1 ms. Every other value schedules as before.

* fix(auth): zero the padding of the token-provider status snapshot

questdb_token_provider_get_status built its output with a struct literal and
copied it out whole, so the padding byte after the three bool fields carried
uninitialized stack: leftover data, or bits of the address of the failure
message copy it had just freed. Callers that compare or hash the struct saw
different bytes for equal snapshots.

Start from a zeroed value, as questdb_error_token_unavailable_get_view and
the OIDC views already do. The new test dirties the stack the call reuses,
so it fails without the fix in both debug and release builds.

* fix(oidc): keep polling after a poll reply cut off mid-body

A device-flow poll whose reply delivered its status line and headers, but
whose body then failed in transit -- the connection closed or reset early,
or the body stalled past the request deadline -- ended the sign-in as a
rejection: "the identity provider rejected the request". The body-read
error carried the response status, and the poll loop took any
non-transient status as a WAF or proxy error page. The IdP's answer is in
the body, so such a reply answered nothing, yet the user's approval in the
browser was lost and only a new sign-in with a new code recovered. The
same fault one step earlier, a drop before the status line, kept the flow
polling.

A body read that fails on a socket error or a deadline now marks the error
response_incomplete. The poll loop handles such a reply as a poll that got
no reply: it keeps polling, applies the RFC 8628 interval increase after a
timeout, and names the failure if the device code expires. A complete
non-JSON reply is still a terminal rejection, and a body over the size cap
or with malformed framing is not marked. The status stays attached, so the
refresh path, which decides from it whether to keep a refresh token, is
unchanged.

* fix(auth): let a shared 401 wait for the running forced refresh

Clients that share a RefreshingTokenProvider see the same 401 at about
the same time when a server stops accepting a token that has not yet
expired. The first rejection forced a fetch and waited for it. Every
other rejection inside forced_min_interval returned at once, so its
client pulled the rejected token straight back, skipped its one 401
replay, and failed: an ILP/HTTP flush with AuthError, whose batch the
Python binding then drops. The QWP/WebSocket and reader 401 replays go
through the same path. Only the first client recovered, though the
replacement token arrived milliseconds later.

A rejection inside the rate limit still starts no fetch, but while the
forced fetch for that same token is running it now waits for it, up to
forced_wait, as the caller that started it does. Once that fetch has
completed, the rate limit applies as before.

Tests: c8_a_rejection_inside_the_rate_limit_waits_for_the_running_forced_fetch
(direct on_rejected and the client replay path) and
test_senders_sharing_a_provider_all_replay_a_shared_401 (two ILP/HTTP
senders against mock servers) fail without the fix and pass with it.

* fix(oidc): refuse loopback sign-in targets from a remote IdP over https

The verification URL a device-flow sign-in opens in the browser, prints
as a link and encodes as a QR code comes from the identity provider.
safe_target refused a loopback URL from a remote IdP only over plain
http, although its contract says a remote IdP must not be able to aim
the browser at whatever else listens on the user's machine. A remote
IdP could still name https://127.0.0.1:9000/exec?query=... -- or
localhost, or [::1] -- and with open_browser on (the default) the
browser opened it, reaching any local TLS service whose certificate it
trusts.

A loopback target is now accepted, over either scheme, only when the
configured IdP endpoint is itself loopback. A local IdP keeps naming
its own port. Names are not resolved, so a public name that resolves to
loopback is not covered; the comment says so.

safe_target_refuses_loopback_targets_from_a_remote_idp now covers https
too and fails without the fix.

* fix(oidc): refuse a symlinked token store however its path is spelled

FileTokenStore refuses a store directory whose final component is a
symbolic link, so a link planted at the store path cannot make it chmod
and write the link's target. The check lstat()s the configured path,
and path resolution follows a final symlink when the path ends in a
separator or `/.`: `<dir>/link/` passed the check that `<dir>/link`
fails, and a sign-in then tightened the link's target to 0700 and wrote
the token file into it. The documented default location,
`${HOME}/.questdb/oidc-tokens/`, invites that spelling in
QUESTDB_CLIENT_OIDC_TOKEN_STORE_DIR, and neither the C setter nor the
Python binding normalises it.

FileTokenStore::at now drops trailing separators and `.` components
once, so every later lstat, chmod and join sees the leaf itself.

Tests: refuses_a_symlinked_store_directory_however_it_is_spelled and
store_directory_drops_trailing_separators_and_dot_components fail
without the fix.

* fix(oidc): refuse every spelling of the local machine as a sign-in target

fab63e5 refused a loopback verification URL from a remote identity
provider, but decided "loopback" with a parser that accepts only
canonical addresses and the exact name `localhost`. Browsers parse a
host the URL Standard way: `127.1`, `2130706433`, `0x7f.0.0.1` and
`0177.0.0.1` all open 127.0.0.1. So a remote IdP could still have
https://127.1:9000/exec?query=... opened in the browser, linkified and
QR-encoded, reaching a local TLS service whose certificate covers
127.0.0.1. `[::ffff:127.0.0.1]`, `0.0.0.0`, `[::]` and `*.localhost`
got through the same way.

safe_target now refuses a host that a browser parses as an IPv4 address
unless it is a canonical dotted quad, whatever the IdP: no identity
provider needs a shorthand spelling. It also treats unspecified
addresses, IPv4-mapped loopback and unspecified addresses, and
subdomains of `localhost` as the local machine, which only a loopback
IdP may name. The plaintext rule is unchanged.

Tests: safe_target_refuses_every_spelling_of_the_local_machine_from_a_remote_idp
fails without the fix.

* fix(auth): stop a 401 waiting out forced_wait while backoff holds the fetch

When a server rejects a RefreshingTokenProvider's token with HTTP 401,
on_rejected forces a fetch and waits up to forced_wait for it. While the
provider was backing off after a failed fetch -- an identity provider
throttling with Retry-After, say -- the forced fetch was refused, yet
the call still waited the whole forced_wait (5 s by default) for a fetch
that could not start, and then handed back the rejected token. Every
ILP/HTTP flush answered 401 in that state stalled 5 s before failing
with the same 401, and since 7f2b01f so did every further 401 inside
forced_min_interval.

on_rejected now returns at once when no fetch is running and backoff
lets none start before its deadline, as a cold token() already does. A
backoff that ends within forced_wait is still waited for.

Tests: c8_a_rejection_returns_at_once_when_backoff_outlasts_the_forced_wait
fails without the fix; c8_a_rejection_still_waits_for_a_backoff_that_ends_within_the_forced_wait
covers the wait that remains.

* fix(cpp): pass on a sender error a token provider lets escape

A C++ bearer_token_provider passes on a classified QuestDB error from
its token() unchanged, so the clients keep the classification: a closed
token_provider's failure stops them as auth_error with provider_closed
set. That works by handing the error's C error to
questdb_token_sink_set_error_from, but line_sender_error::from_c freed
its C error instead of keeping it. A line_sender_error escaping token()
-- the one opts::token_provider() throws for a closed provider, say --
was therefore re-reported as terminal: every client failed with
config_error and no classification, contrary to the documented
contract. One carrying OIDC detail lost that detail and was reported as
an ordinary retryable failure.

line_sender_error::from_c now keeps the C error, as questdb::error does,
and report_current_exception passes on one carrying a classification or
OIDC detail.

Tests: "A provider passing on a sender error keeps its classification"
and "... keeps its OIDC detail" fail without the fix.

* docs: link the OIDC headers and examples from the C and C++ guides

doc/C.md and doc/CPP.md list the committed headers as the authoritative
native API reference, and the token-provider header and example were
added there, but not oidc.h, oidc.hpp or the OIDC examples, so a C or
C++ user found no route to the device-flow API. SECURITY.md discussed
the OIDC device flow but linked only the token-provider material.

* fix(oidc): count every non-spacing mark against the display stacking cap

sanitize_display_text keeps at most four combining marks stacked on one
base character, so that untrusted text -- an identity provider's
error_description, an OIDC error message -- cannot smear a runaway
"Zalgo" stack across the lines around it. It counted only marks from a
list of stacking blocks, and any other kept character ended the run,
including a combining mark outside those blocks. Interleaving such a
mark with listed ones (`A` followed by 99 pairs of U+0951 U+0301) kept
all 198 marks on one base character in the native stderr renderer,
questdb_error_msg, the error view's idp_error_description and C FAILURE
events, while the Python client, whose cap the docs said this matched,
kept four.

Every code point of general category Mn now counts, as in the Python
client. A generated table of the Unicode 16.0.0 Mn ranges replaces the
block list, which it contains; it is data, not a crate dependency.

Tests: strip_control_counts_every_nonspacing_mark_in_a_run fails without
the fix; nonspacing_marks_are_sorted_and_disjoint guards the table's
binary search.

* docs(auth): say that closing a token provider does not wait for its fetch

questdb_token_provider_close, the last questdb_token_provider_free and
RefreshingTokenProvider::close return while a source call already in
flight keeps running on the refresher thread; its result is discarded,
and release runs only after it returns. The headers said close "stops
its refresher", and nothing told C callers that the source may still
run, so a caller that freed what the source uses right after close and
free -- user_data without a release, a global, a library -- could have
it used after free. The OIDC handles in the same headers state their
in-flight guarantees.

token_provider.h, token_provider.hpp and the Rust docs now say so, and
tell C callers to tear down what the source uses from release, and C++
callers to capture by value or keep what the source refers to alive
until the provider drops its copy. Behaviour is unchanged.

* fix(oidc): keep a local IdP's sign-in target however its host is spelled

cbbfb7a refused a target on keycloak.localhost, 0.0.0.0 or an
IPv4-mapped loopback address unless the configured IdP is itself on the
local machine. But the IdP side was still judged by is_loopback, which
knows only loopback addresses and the exact name localhost. An IdP
configured on one of those spellings therefore counted as remote, and its
own verification URL was refused: no browser open, no "open directly"
line, a NULL browser_target in the C prompt event, and a defanged URL in
the terminal prompt. Sign-in itself still completed.

Both sides of the rule now use one test, render::is_local_machine. The
plaintext rules are unchanged: an http IdP or target must still be
loopback.

Test: an_idp_on_the_local_machine_keeps_its_verification_url_however_it_is_spelled
fails without the fix (browser_target is None for keycloak.localhost).
@glasstiger glasstiger changed the title fix(qwp)!: cap config and callback inputs, harden failover and shutdown paths fix(qwp): cap config and callback inputs, harden failover and shutdown paths Nov 16, 2026
@glasstiger glasstiger changed the title fix(qwp): cap config and callback inputs, harden failover and shutdown paths fix(client)!: bound inputs and harden HTTP, failover, and shutdown Nov 16, 2026
@glasstiger glasstiger changed the title fix(client)!: bound inputs and harden HTTP, failover, and shutdown fix(qwp)!: bound inputs and harden HTTP, failover, and shutdown Nov 16, 2026
@glasstiger

Copy link
Copy Markdown
Contributor Author

superseded by #228

@glasstiger glasstiger closed this Nov 16, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant