Skip to content
Open
7 changes: 5 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -678,8 +678,11 @@ The ingest side also accepts store-and-forward and reconnection tuning keys (`au
is the minimum working set every live sender keeps: two segments (`2 × sf_max_segment_bytes`, 8 MiB by default).
`sf_durability=periodic` checkpoints mmap-published data in the background; `sf_sync_interval_millis` defaults to `5000`
in that mode. The interval is a target cadence: JVM scheduling and storage-sync latency add to the actual loss window.
Use `request_durable_ack=on` when end-to-end server durability is also required. See the
[QuestDB documentation](https://questdb.com/docs/) for the full reference.
Use `request_durable_ack=on` when end-to-end server durability is also required. `owned_by=<group>` names the owner
of the tables and columns the sender auto-creates, like `OWNED BY` in SQL (QuestDB Enterprise): the server grants them to
that group instead of the authenticated user, and an external user, such as one signed in with OpenID Connect, must name
one of its groups to auto-create anything. See the [QuestDB documentation](https://questdb.com/docs/) for the full
reference.

## Requirements

Expand Down
49 changes: 48 additions & 1 deletion core/src/main/java/io/questdb/client/Sender.java
Original file line number Diff line number Diff line change
Expand Up @@ -1221,6 +1221,8 @@ public int getConnectTimeout() {
};
private long minRequestThroughput = PARAMETER_NOT_SET_EXPLICITLY;
private int multicastTtl = PARAMETER_NOT_SET_EXPLICITLY;
// Owner of the tables and columns the sender auto-creates (WebSocket only), or null.
private String ownedBy;
private String password;
private PrivateKey privateKey;
private int protocol = PARAMETER_NOT_SET_EXPLICITLY;
Expand Down Expand Up @@ -2556,6 +2558,39 @@ public LineSenderBuilder multicastTtl(int multicastTtl) {
return this;
}

/**
* Names the owner of the tables and columns this sender auto-creates, the way the {@code OWNED BY}
* clause of {@code CREATE TABLE} and {@code ALTER TABLE ... ADD COLUMN} does in SQL: the server grants
* the new tables and columns to this user, group or service account instead of the authenticated
* principal. The principal may name itself or one of its groups, and the built-in admin any existing
* entity but an external user. An external user, for example one authenticated with an OpenID Connect
* token, cannot own anything itself, so it must name one of its groups to have tables or columns
* auto-created at all.
* <p>
* The owner is sent once per connection, in the WebSocket upgrade, and checked there: a server that
* refuses it rejects the connection, and a server that does not confirm it, one without the feature,
* fails it. Requires QuestDB Enterprise with access control enabled.
* <p>
* This setting is only supported for WebSocket transport.
*
* @param owner name of the user, group or service account to own the auto-created tables and columns
* @return this instance for method chaining
*/
public LineSenderBuilder ownedBy(String owner) {
if (this.ownedBy != null) {
throw new LineSenderException("owned_by was already configured ")
.put("[ownedBy=").put(this.ownedBy).put("]");
}
if (Chars.isBlank(owner)) {
throw new LineSenderException("owned_by cannot be empty nor null");
}
if (protocol != PARAMETER_NOT_SET_EXPLICITLY && protocol != PROTOCOL_WEBSOCKET) {
throw new LineSenderException("owned_by is only supported for WebSocket transport");
}
this.ownedBy = owner;
return this;
}

/**
* Set port where a QuestDB server is listening on.
*
Expand Down Expand Up @@ -3769,7 +3804,8 @@ private QwpWebSocketSender buildWebSocket(HttpTokenProvider tokenProvider) {
symbolDictReset,
actualSymbolDictResetThreshold,
actualSymbolDictResetMaxWaitMillis,
keepaliveIntervalMillis
keepaliveIntervalMillis,
ownedBy
);
} catch (UnreplayableSlotException e) {
// The one failure build() recovers from. The slot's frames reference ids
Expand Down Expand Up @@ -4211,6 +4247,9 @@ private LineSenderBuilder fromConfig(CharSequence configurationString) {
int protocolVersion = parseIntValue(sink, "protocol_version");
protocolVersion(protocolVersion);
}
} else if (Chars.equals("owned_by", sink)) {
// ws/wss strings never reach this parser, see fromConfigWebSocket()
throw new LineSenderException("owned_by is only supported for WebSocket transport");
} else if (Chars.equals("request_durable_ack", sink)) {
if (protocol != PROTOCOL_WEBSOCKET) {
throw new LineSenderException("request_durable_ack is only supported for WebSocket transport");
Expand Down Expand Up @@ -4686,6 +4725,10 @@ private LineSenderBuilder fromConfigWebSocket(CharSequence configurationString)
throw new LineSenderException("invalid transaction [value=").put(s).put(", allowed-values=[on, off]]");
}
}
s = view.getStr("owned_by");
if (s != null) {
ownedBy(s);
}
s = view.getStr("request_durable_ack");
if (s != null) {
int tiers = DurableAckTiers.parseConfigValue(s);
Expand Down Expand Up @@ -4823,6 +4866,7 @@ public java.util.Map<String, Object> wsConfigSnapshotForTest() {
m.put("max_name_len", maxNameLength);
m.put("transaction", transactional);
m.put("request_durable_ack", DurableAckTiers.configValue(durableAckTiers));
m.put("owned_by", ownedBy);
m.put("sender_id", senderId);
m.put("sf_dir", sfDir);
m.put("sf_max_segment_bytes", sfMaxSegmentBytes);
Expand Down Expand Up @@ -4945,6 +4989,9 @@ private void validateParameters() {
if (durableAckTiers != DurableAckTiers.NONE && protocol != PROTOCOL_WEBSOCKET) {
throw new LineSenderException("request_durable_ack is only supported for WebSocket transport");
}
if (ownedBy != null && protocol != PROTOCOL_WEBSOCKET) {
throw new LineSenderException("owned_by is only supported for WebSocket transport");
}
if (protocol == PROTOCOL_HTTP) {
if (httpClientConfiguration.getMaximumRequestBufferSize() < httpClientConfiguration.getInitialRequestBufferSize()) {
throw new LineSenderException("maximum buffer capacity cannot be less than initial buffer capacity ")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,9 @@
package io.questdb.client.cutlass.http.client;

import io.questdb.client.HttpClientConfiguration;
import io.questdb.client.cutlass.auth.CredentialRedaction;
import io.questdb.client.cutlass.qwp.client.DurableAckTiers;
import io.questdb.client.cutlass.qwp.client.QwpOwnedByMismatchException;
import io.questdb.client.cutlass.qwp.client.QwpVersionMismatchException;
import io.questdb.client.cutlass.qwp.websocket.WebSocketCloseCode;
import io.questdb.client.cutlass.qwp.websocket.WebSocketFrameParser;
Expand Down Expand Up @@ -75,15 +77,20 @@ public abstract class WebSocketClient implements QuietCloseable {
private static final int DEFAULT_RECV_BUFFER_SIZE = 65536;
private static final int DEFAULT_SEND_BUFFER_SIZE = 65536;
private static final Logger LOG = LoggerFactory.getLogger(WebSocketClient.class);
// Cap on the body bytes of a rejected upgrade read for its reason, see extractRejectReason().
private static final int MAX_REJECT_REASON_BYTES = 4096;
// tryParseFrame() return values
private static final int PARSE_INCOMPLETE = 0;
private static final int PARSE_NEED_MORE = -1;
private static final int PARSE_OK = 1;
// Upper-case, as RFC 3986 section 2.1 recommends for percent-encoding, and as the server echoes it.
private static final char[] PERCENT_ENCODING_HEX_DIGITS = "0123456789ABCDEF".toCharArray();
private static final String QUESTDB_ROLE_HEADER_NAME = "X-QuestDB-Role:";
private static final String QUESTDB_ZONE_HEADER_NAME = "X-QuestDB-Zone:";
private static final String QWP_CONTENT_ENCODING_HEADER_NAME = "X-QWP-Content-Encoding:";
private static final String QWP_DURABLE_ACK_HEADER_NAME = "X-QWP-Durable-Ack:";
private static final String QWP_MAX_BATCH_SIZE_HEADER_NAME = "X-QWP-Max-Batch-Size:";
private static final String QWP_OWNED_BY_HEADER_NAME = "X-QWP-Owned-By:";
private static final String QWP_VERSION_HEADER_NAME = "X-QWP-Version:";
private static final ThreadLocal<MessageDigest> SHA1_DIGEST = ThreadLocal.withInitial(() -> {
try {
Expand Down Expand Up @@ -145,6 +152,10 @@ public abstract class WebSocketClient implements QuietCloseable {
// down to its own hard limit.
private int qwpMaxBatchRows;
private int qwpMaxVersion = 1;
// Owner of the tables and columns the connection auto-creates, or null, and its X-QWP-Owned-By value,
// percent-encoded by encodeOwnedBy(). The server echoes the value in the 101 response when it accepts it.
private String qwpOwnedBy;
private String qwpOwnedByHeaderValue;
// Requested durable-ack tier set (DurableAckTiers bitmask), sent as
// X-QWP-Request-Durable-Ack: <DurableAckTiers.requestHeaderValue>
private int qwpDurableAckTiers = DurableAckTiers.NONE;
Expand Down Expand Up @@ -178,6 +189,10 @@ public abstract class WebSocketClient implements QuietCloseable {
// the wire said without re-clamping so a misconfigured server is observable.
private int serverNegotiatedZstdLevel;
private int serverQwpVersion = 1;
// Plain-text body of the most recent rejected upgrade, sanitized for display, or null when the response
// carried none or it had not fully arrived with the headers. QuestDB explains some refusals there, such
// as a refused owned_by. Reset to null on every upgrade() invocation.
private String upgradeRejectReason;
private String upgradeRejectRole;
// WWW-Authenticate value(s) from the most recent rejected upgrade, joined with ", " when the server sent
// several, or null when absent. Lets a 401 carrying "Bearer error=insufficient_scope" be told apart from an
Expand Down Expand Up @@ -241,6 +256,27 @@ public WebSocketClient(HttpClientConfiguration configuration, SocketFactory sock
}
}

/**
* Returns the {@code X-QWP-Owned-By} encoding of an owner name: its UTF-8 bytes, the RFC 3986 unreserved
* characters as they are and every other byte as {@code %XX} with upper-case hex digits. That keeps a
* name outside ASCII intact through proxies, and it is the canonical form the server echoes the accepted
* owner in, so the echo can be compared to what was sent.
*/
public static String encodeOwnedBy(String ownedBy) {
final byte[] utf8 = ownedBy.getBytes(StandardCharsets.UTF_8);
final StringBuilder sb = new StringBuilder(utf8.length);
for (byte b : utf8) {
if (isUnreservedByte(b)) {
sb.append((char) b);
} else {
sb.append('%')
.append(PERCENT_ENCODING_HEX_DIGITS[(b >> 4) & 0xF])
.append(PERCENT_ENCODING_HEX_DIGITS[b & 0xF]);
}
}
return sb.toString();
}

/**
* Appends one binary frame to the send batch, back to back with any frame
* already appended. Nothing reaches the wire until {@link #batchFlush()}.
Expand Down Expand Up @@ -439,6 +475,15 @@ public int getServerQwpVersion() {
return serverQwpVersion;
}

/**
* Plain-text body of the most recent rejected upgrade, sanitized for display, or null when the response
* carried none, or it had not fully arrived with the headers. QuestDB explains some refusals there, such
* as an {@code owned_by} the principal may not name.
*/
public String getUpgradeRejectReason() {
return upgradeRejectReason;
}

/**
* Role from {@code X-QuestDB-Role} on the most recent rejected upgrade,
* or null when no such header was present.
Expand Down Expand Up @@ -670,6 +715,17 @@ public void setQwpMaxVersion(int maxVersion) {
this.qwpMaxVersion = maxVersion;
}

/**
* Names the owner of the tables and columns the connection auto-creates, sent in the
* {@code X-QWP-Owned-By} upgrade header, see {@link #encodeOwnedBy}. The upgrade fails with a
* {@link WebSocketUpgradeException} unless the server echoes it, as a server that does not support the
* header ignores it. {@code null} (the default) omits the header. Must be called before {@link #upgrade}.
*/
public void setQwpOwnedBy(String ownedBy) {
this.qwpOwnedBy = ownedBy;
this.qwpOwnedByHeaderValue = ownedBy == null ? null : encodeOwnedBy(ownedBy);
}

/**
* Sets the requested durable-ack tier set ({@link DurableAckTiers}
* bitmask) for the opt-in X-QWP-Request-Durable-Ack upgrade header. When
Expand Down Expand Up @@ -742,6 +798,7 @@ public void upgrade(CharSequence path, int timeout, CharSequence authorizationHe
if (upgraded) {
return; // Already upgraded
}
upgradeRejectReason = null;
upgradeRejectRole = null;
upgradeRejectWwwAuthenticate = null;
upgradeRejectZone = null;
Expand Down Expand Up @@ -795,6 +852,11 @@ public void upgrade(CharSequence path, int timeout, CharSequence authorizationHe
sendBuffer.putAscii(DurableAckTiers.requestHeaderValue(qwpDurableAckTiers));
sendBuffer.putAscii("\r\n");
}
if (qwpOwnedByHeaderValue != null) {
sendBuffer.putAscii("X-QWP-Owned-By: ");
sendBuffer.putAscii(qwpOwnedByHeaderValue);
sendBuffer.putAscii("\r\n");
}
if (authorizationHeader != null) {
sendBuffer.putAscii("Authorization: ");
sendBuffer.putAscii(authorizationHeader);
Expand Down Expand Up @@ -1023,6 +1085,12 @@ private static String extractZoneHeader(String response) {
return null;
}

// RFC 3986 section 2.3
private static boolean isUnreservedByte(byte b) {
return (b >= 'A' && b <= 'Z') || (b >= 'a' && b <= 'z') || (b >= '0' && b <= '9')
|| b == '-' || b == '.' || b == '_' || b == '~';
}

private static int parseStatusCode(String statusLine) {
int sp1 = statusLine.indexOf(' ');
if (sp1 < 0 || sp1 + 4 > statusLine.length()) return 0;
Expand Down Expand Up @@ -1204,6 +1272,34 @@ private void doSend(long ptr, int len, int timeout) {
}
}

// The plain-text body of a rejected upgrade, sanitized for display, when the bytes received with the
// headers hold all of it, or null. Best effort: it waits for no more bytes, and a body that is not
// text/plain with a Content-Length, such as a chunked one or a proxy's HTML page, yields none.
private String extractRejectReason(String response, int headerEnd) {
final String contentType = extractHeaderValues(response, "Content-Type:");
final String contentLength = extractHeaderValues(response, "Content-Length:");
if (contentType == null || contentLength == null
|| !contentType.regionMatches(true, 0, "text/plain", 0, "text/plain".length())) {
return null;
}
final int length;
try {
length = Integer.parseInt(contentLength);
} catch (NumberFormatException e) {
return null;
}
if (length <= 0 || length > recvPos - headerEnd) {
return null;
}
final int n = Math.min(length, MAX_REJECT_REASON_BYTES);
final byte[] bytes = new byte[n];
for (int i = 0; i < n; i++) {
bytes[i] = Unsafe.getUnsafe().getByte(recvBufPtr + headerEnd + i);
}
final String reason = new String(bytes, StandardCharsets.UTF_8).trim();
return reason.isEmpty() ? null : CredentialRedaction.sanitizeErrorText(reason);
}

private int findHeaderEnd() {
// Look for \r\n\r\n
for (int i = 0; i < recvPos - 3; i++) {
Expand Down Expand Up @@ -1489,9 +1585,13 @@ private void validateUpgradeResponse(int headerEnd) {
upgradeRejectRole = extractRoleHeader(response);
upgradeRejectZone = extractZoneHeader(response);
}
upgradeRejectReason = extractRejectReason(response, headerEnd);
WebSocketUpgradeException ex = new WebSocketUpgradeException(
upgradeStatusCode, upgradeRejectRole, "WebSocket upgrade failed: ");
ex.put(statusLine);
if (upgradeRejectReason != null) {
ex.put(" [reason=").put(upgradeRejectReason).put(']');
}
throw ex;
}

Expand Down Expand Up @@ -1548,6 +1648,23 @@ private void validateUpgradeResponse(int headerEnd) {
// 0 means "no zstd" (raw transport, or header absent on older
// servers); non-zero is the applied level.
serverNegotiatedZstdLevel = extractContentEncodingZstdLevel(response);

// A server that accepts the owner echoes it in X-QWP-Owned-By; one that
// refuses it rejects the upgrade instead. No echo means a server that
// does not know the header and ignored it, so the tables this client
// auto-creates would not get the owner. The failure fails the initial
// connect, also when another endpoint of the round answered 421, while a
// sender that has connected before keeps retrying it, as it retries every
// upgrade policy failure, and an orphan drainer retries it within its
// capability-gap settle budget, as it does a missing durable-ack echo. It
// carries no status, as the server answered 101 and so did not reject the
// upgrade itself. See QwpOwnedByMismatchException.
if (qwpOwnedByHeaderValue != null) {
String echo = extractHeaderValues(response, QWP_OWNED_BY_HEADER_NAME);
if (!qwpOwnedByHeaderValue.equals(echo)) {
throw new QwpOwnedByMismatchException(qwpOwnedBy, echo);
}
}
}

protected void dieWaiting(int n) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,14 @@

/**
* Thrown by {@link WebSocketClient#upgrade} when the server returns a non-101
* status. Carries the status code and the server role (parsed from the
* status, or a 101 that does not confirm the {@code owned_by} the client
* requested (the subclass
* {@link io.questdb.client.cutlass.qwp.client.QwpOwnedByMismatchException},
* status {@link #STATUS_NONE}, see {@link WebSocketClient#setQwpOwnedBy}).
* Carries the status code and the server role (parsed from the
* {@code X-QuestDB-Role} header) so callers can distinguish a transient
* role-mismatch (status 421 against a REPLICA / PRIMARY_CATCHUP node) from
* a terminal upgrade rejection (e.g. 401, 403, 426).
* role-mismatch (status 421 against a REPLICA / PRIMARY_CATCHUP node) from a
* terminal upgrade rejection (e.g. 401, 403, 426).
*/
public class WebSocketUpgradeException extends HttpClientException {

Expand All @@ -53,8 +57,9 @@ public String getServerRole() {
}

/**
* The HTTP status code from the upgrade response, or {@link #STATUS_NONE}
* if the response could not be parsed.
* The HTTP status code of the rejected upgrade response ({@code 0} when its
* status line could not be parsed), or {@link #STATUS_NONE} when the server
* answered 101 but did not confirm the {@code owned_by} the client requested.
*/
public int getStatusCode() {
return statusCode;
Expand Down
Loading
Loading