Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -21,20 +21,47 @@
import com.arcadedb.log.LogManager;
import com.arcadedb.server.http.HttpServer;
import io.undertow.server.HttpServerExchange;
import io.undertow.util.AttachmentKey;
import io.undertow.util.StatusCodes;

import java.util.concurrent.atomic.AtomicReference;
import java.util.logging.Level;

/**
* Base handler for endpoints that receive binary (non-JSON) request bodies.
* Base handler for database-scoped endpoints that receive binary (non-JSON) request bodies.
* Captures raw bytes from the request instead of interpreting them as a string.
* <p>
* On {@link DatabaseAbstractHandler} since issue #7681. Both of its subclasses - the Prometheus
* {@code remote_write} and {@code remote_read} endpoints under {@code /api/v1/ts/{database}/prom} - are
* database-scoped and had to start honouring {@code arcadedb-session-id}, and Java has one superclass to
* spend. The command that says these two are the whole population:
* <pre>
* $ grep -rn "extends AbstractBinaryHttpHandler" --include="*.java" .
* ./server/src/main/java/com/arcadedb/server/http/handler/PostPrometheusReadHandler.java
* ./server/src/main/java/com/arcadedb/server/http/handler/PostPrometheusWriteHandler.java
* </pre>
* A future binary endpoint that is NOT database-scoped therefore cannot use this class as-is; it would want
* the body capture below over {@code AbstractServerHttpHandler} instead.
*
* @author Luca Garulli (l.garulli@arcadedata.com)
*/
public abstract class AbstractBinaryHttpHandler extends AbstractServerHttpHandler {

protected byte[] rawBytes;
public abstract class AbstractBinaryHttpHandler extends DatabaseAbstractHandler {
/**
* This request's body, attached to the exchange rather than kept in a field.
* <p>
* It used to be an instance field, and a handler is a SINGLETON - one instance is registered on the route and
* serves every request. {@link #parseRequestPayload} and {@code execute} are two separate calls from
* {@code AbstractServerHttpHandler.handleRequest}, with authentication, the idempotency reservation and the
* session resolution in between, so two concurrent requests interleaved as: T1 parses body1, T2 overwrites
* the field with body2, T1 executes against T2's bytes, T2 executes against them again. On
* {@code POST /api/v1/ts/{database}/prom/write} that silently ingests one remote-write payload twice and
* loses the other, and Prometheus remote-write is a path whose normal deployment is several concurrent
* shippers. This is the same defect issue #7683 reported for {@code PostTimeSeriesWriteHandler}'s string
* body, in the class that holds the byte one; moving these handlers onto {@link DatabaseAbstractHandler}
* widens the window by adding the session resolution to what runs between the two calls, so it is fixed in
* the same change rather than left wider than it was found.
*/
private static final AttachmentKey<byte[]> RAW_BINARY_PAYLOAD = AttachmentKey.create(byte[].class);

public AbstractBinaryHttpHandler(final HttpServer httpServer) {
super(httpServer);
Expand All @@ -50,6 +77,13 @@ protected boolean requiresJsonPayload() {
return false;
}

/**
* The bytes THIS request arrived with, or {@code null} when the body was empty or could not be read.
*/
protected static byte[] rawBytes(final HttpServerExchange exchange) {
return exchange.getAttachment(RAW_BINARY_PAYLOAD);
}

@Override
protected String parseRequestPayload(final HttpServerExchange e) {
if (!e.isInIoThread() && !e.isBlocking())
Expand All @@ -63,7 +97,10 @@ protected String parseRequestPayload(final HttpServerExchange e) {
exchange.setStatusCode(StatusCodes.INTERNAL_SERVER_ERROR);
exchange.getResponseSender().send("Invalid Request");
});
rawBytes = result.get();

final byte[] body = result.get();
if (body != null)
e.putAttachment(RAW_BINARY_PAYLOAD, body);
return null; // no string payload needed
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -300,6 +300,31 @@ private void cleanTL(final Database database, DatabaseContext.DatabaseContextTL
}
}

/**
* Whether this request names a session at all - the one question a {@link #mustExecuteOnWorkerThread(HttpServerExchange)}
* override needs in order to keep answering a session-less request on the IO thread while dispatching a
* session-scoped one to a worker.
* <p>
* It has to be asked, because a session-scoped request runs inside {@code HttpSession.execute}, which blocks
* on the session lock for up to five seconds. An Undertow IO thread serves many connections, so that wait is
* not paid by the caller that queued behind its own session: it is paid by every unrelated connection
* multiplexed onto the same thread. Introduced with {@code GET /api/v1/ts/{database}/latest} in issue #7402
* and shared from here since issue #7681, which put eight more IO-thread handlers on this base class.
* <p>
* Only tests the header's presence, which is deliberately the SAME test {@link #setTransactionInThreadLocal}
* and {@link #removeSession} make on the same header - all three read it as
* {@code sessionId != null && !sessionId.isEmpty()}, where {@code isEmpty()} asks whether the header carries
* any value at all, not whether that value is blank. Keeping them identical is the point: this method decides
* which THREAD the request is answered on and that one decides what the id RESOLVES to, so tightening one
* without the other would answer a request on the IO thread and then block it on the session lock anyway, or
* dispatch one that was never going to touch a session. A value that turns out not to resolve has by then
* cost a dispatch, which is the cheap half of the trade (claude-review on PR #7723).
*/
protected boolean carriesSessionId(final HttpServerExchange exchange) {
final HeaderValues sessionId = exchange.getRequestHeaders().get(SESSION_ID_HEADER);
return sessionId != null && !sessionId.isEmpty();
}

protected boolean requiresDatabase() {
return true;
}
Expand Down Expand Up @@ -389,9 +414,10 @@ protected HttpSession setTransactionInThreadLocal(final HttpServerExchange excha
// The session id is not resolvable (committed/rolled back, expired, or owned by another principal).
// A write-capable handler MUST reject it: falling through session-less would run the command in an
// implicit auto-committing transaction while the client believes it is inside a transaction it can
// still roll back. Read-only handlers (GET /query, the two /api/v1/ts read routes) and the transaction
// endpoints (/begin, /commit, /rollback) instead degrade to a session-less request, keeping
// read-after-commit and idempotent retries of commit/rollback working.
// still roll back. Read-only handlers (GET /query, and the nine read routes under /api/v1/ts that
// issues #7402 and #7681 moved onto this class) and the transaction endpoints (/begin, /commit,
// /rollback) instead degrade to a session-less request, keeping read-after-commit and idempotent
// retries of commit/rollback working.
if (rejectsUnresolvableSession())
throw new HttpSessionException("Remote transaction '" + sessionId.getFirst() + "' not found or expired");

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,43 +18,63 @@
*/
package com.arcadedb.server.http.handler;

import com.arcadedb.database.Database;
import com.arcadedb.serializer.json.JSONObject;
import com.arcadedb.server.http.HttpServer;
import com.arcadedb.server.security.ServerSecurityUser;
import io.undertow.server.HttpServerExchange;

import java.util.Deque;

/**
* Grafana health-check endpoint.
* Endpoint: GET /api/v1/ts/{database}/grafana/health
* <p>
* On {@link DatabaseAbstractHandler} since issue #7681, for the reasons spelled out on
* {@link PostGrafanaQueryHandler}: a request carrying {@code arcadedb-session-id} is answered inside that
* session - under its lock, on its principal, refreshing the idle timer that decides when its transaction is
* rolled back underneath it - and the base class subsumes the {@code checkAuthorizationOnDatabase} call this
* handler used to make by hand.
* <p>
* Resolving the database is now the base class's job, which is also what this handler's own body used to do
* one line later purely to make a missing database throw. The one difference that follows: a health check
* against a database that does not exist is refused BEFORE the session is resolved rather than after, which is
* the same 404 it answered before.
*/
public class GetGrafanaHealthHandler extends AbstractServerHttpHandler {
public class GetGrafanaHealthHandler extends DatabaseAbstractHandler {

public GetGrafanaHealthHandler(final HttpServer httpServer) {
super(httpServer);
}

/**
* A health check reads nothing, so an auto-commit wrapper around it would only add a commit with nothing to
* commit. A consequence of that answer, shared with every other read on this prefix, is that an unresolvable
* session id degrades to a session-less check rather than being refused - see
* {@link DatabaseAbstractHandler#rejectsUnresolvableSession()}.
*/
@Override
protected ExecutionResponse execute(final HttpServerExchange exchange, final ServerSecurityUser user,
final JSONObject payload) throws Exception {

final Deque<String> databaseParam = exchange.getQueryParameters().get("database");
if (databaseParam == null || databaseParam.isEmpty())
return new ExecutionResponse(400, "{ \"error\" : \"Database parameter is required\"}");

final String databaseName = databaseParam.getFirst();
protected boolean requiresTransaction() {
return false;
}

// Enforce database-level authorization (GHSA-x8mg-6r4p-87pf): this handler does not extend
// DatabaseAbstractHandler. Also prevents this endpoint from being a cross-database existence oracle.
checkAuthorizationOnDatabase(user, databaseName);
/**
* A session-less health check is short enough to answer on the IO thread, which is what this handler has
* always done. A request that names a session is not: see {@link DatabaseAbstractHandler#carriesSessionId}.
*/
@Override
protected boolean mustExecuteOnWorkerThread(final HttpServerExchange exchange) {
return carriesSessionId(exchange);
}

// Verify the database exists (will throw if not)
httpServer.getServer().getDatabase(databaseName, false, false);
@Override
protected ExecutionResponse execute(final HttpServerExchange exchange, final ServerSecurityUser user,
final Database db, final JSONObject payload) throws Exception {

final JSONObject result = new JSONObject();
result.put("status", "ok");
result.put("database", databaseName);
// The name as the caller spelled it in the path, which is what this response has always echoed. Taken from
// the parameter rather than from db.getName() so the echo cannot start disagreeing with the request if the
// server ever resolves a name through an alias.
result.put("database", exchange.getQueryParameters().get("database").getFirst());

return new ExecutionResponse(200, result.toString());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
*/
package com.arcadedb.server.http.handler;

import com.arcadedb.database.Database;
import com.arcadedb.database.DatabaseInternal;
import com.arcadedb.engine.timeseries.AggregationType;
import com.arcadedb.engine.timeseries.ColumnDefinition;
Expand All @@ -31,31 +32,46 @@
import com.arcadedb.server.security.ServerSecurityUser;
import io.undertow.server.HttpServerExchange;

import java.util.Deque;

/**
* Grafana metadata endpoint — discovers TimeSeries types, fields, and tags.
* Endpoint: GET /api/v1/ts/{database}/grafana/metadata
* <p>
* On {@link DatabaseAbstractHandler} since issue #7681, for the reasons spelled out on
* {@link PostGrafanaQueryHandler}. It matters more here than on a plain read: what this endpoint reports is
* the SCHEMA, and a type created inside the caller's open transaction is visible to that transaction and to
* nothing else. Answered from outside the session, a panel that had just created a type was told the type
* does not exist.
*/
public class GetGrafanaMetadataHandler extends AbstractServerHttpHandler {
public class GetGrafanaMetadataHandler extends DatabaseAbstractHandler {

public GetGrafanaMetadataHandler(final HttpServer httpServer) {
super(httpServer);
}

/**
* A read: an auto-commit wrapper would only add a commit with nothing to commit, and an unresolvable session
* id therefore degrades rather than being refused - see
* {@link DatabaseAbstractHandler#rejectsUnresolvableSession()}.
*/
@Override
protected ExecutionResponse execute(final HttpServerExchange exchange, final ServerSecurityUser user,
final JSONObject payload) throws Exception {
protected boolean requiresTransaction() {
return false;
}

final Deque<String> databaseParam = exchange.getQueryParameters().get("database");
if (databaseParam == null || databaseParam.isEmpty())
return new ExecutionResponse(400, "{ \"error\" : \"Database parameter is required\"}");
/**
* A session-less schema walk is short enough to answer on the IO thread, which is what this handler has
* always done. A request that names a session is not: see {@link DatabaseAbstractHandler#carriesSessionId}.
*/
@Override
protected boolean mustExecuteOnWorkerThread(final HttpServerExchange exchange) {
return carriesSessionId(exchange);
}

// Enforce database-level authorization (GHSA-x8mg-6r4p-87pf): this handler does not extend DatabaseAbstractHandler.
// Checked before any payload/parameter validation so an unauthorized caller cannot probe the target database.
checkAuthorizationOnDatabase(user, databaseParam.getFirst());
@Override
protected ExecutionResponse execute(final HttpServerExchange exchange, final ServerSecurityUser user,
final Database db, final JSONObject payload) throws Exception {

final DatabaseInternal database = httpServer.getServer().getDatabase(databaseParam.getFirst(), false, false);
final DatabaseInternal database = (DatabaseInternal) db;

final JSONArray typesArray = new JSONArray();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
*/
package com.arcadedb.server.http.handler;

import com.arcadedb.database.Database;
import com.arcadedb.database.DatabaseInternal;
import com.arcadedb.engine.timeseries.ColumnDefinition;
import com.arcadedb.engine.timeseries.TimeSeriesEngine;
Expand All @@ -41,32 +42,49 @@
/**
* HTTP handler for listing PromQL label values.
* Endpoint: GET /api/v1/ts/{database}/prom/api/v1/label/{name}/values
* <p>
* On {@link DatabaseAbstractHandler} since issue #7681, for the reasons spelled out on
* {@link PostGrafanaQueryHandler}: a request carrying {@code arcadedb-session-id} reads through that session's
* transaction, under its lock and on its principal and refreshing its idle timer, and the base class subsumes
* the {@code checkAuthorizationOnDatabase} call this handler used to make by hand.
*
* @author Luca Garulli (l.garulli@arcadedata.com)
*/
public class GetPromQLLabelValuesHandler extends AbstractServerHttpHandler {
public class GetPromQLLabelValuesHandler extends DatabaseAbstractHandler {

public GetPromQLLabelValuesHandler(final HttpServer httpServer) {
super(httpServer);
}

/**
* A read: an auto-commit wrapper would only add a commit with nothing to commit, so an unresolvable session
* id degrades to a session-less read rather than being refused - see
* {@link DatabaseAbstractHandler#rejectsUnresolvableSession()}.
*/
@Override
protected ExecutionResponse execute(final HttpServerExchange exchange, final ServerSecurityUser user,
final JSONObject payload) throws Exception {
protected boolean requiresTransaction() {
return false;
}

final Deque<String> databaseParam = exchange.getQueryParameters().get("database");
if (databaseParam == null || databaseParam.isEmpty())
return new ExecutionResponse(400, PromQLResponseFormatter.formatError("bad_data", "Database parameter is required"));
/**
* A session-less read is answered on the IO thread, which is what this handler has always done. A request
* that names a session is not: see {@link DatabaseAbstractHandler#carriesSessionId}.
*/
@Override
protected boolean mustExecuteOnWorkerThread(final HttpServerExchange exchange) {
return carriesSessionId(exchange);
}

// Enforce database-level authorization (GHSA-x8mg-6r4p-87pf): this handler does not extend DatabaseAbstractHandler.
// Checked before any payload/parameter validation so an unauthorized caller cannot probe the target database.
checkAuthorizationOnDatabase(user, databaseParam.getFirst());
@Override
protected ExecutionResponse execute(final HttpServerExchange exchange, final ServerSecurityUser user,
final Database db, final JSONObject payload) throws Exception {

final Deque<String> nameParam = exchange.getQueryParameters().get("name");
if (nameParam == null || nameParam.isEmpty())
return new ExecutionResponse(400, PromQLResponseFormatter.formatError("bad_data", "Label name parameter is required"));

final String labelName = nameParam.getFirst();
final DatabaseInternal database = httpServer.getServer().getDatabase(databaseParam.getFirst(), false, false);
final DatabaseInternal database = (DatabaseInternal) db;

final Set<String> values = new LinkedHashSet<>();

Expand Down
Loading
Loading