Skip to content
Open
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
1 change: 1 addition & 0 deletions include/fluent-bit/flb_http_client.h
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,7 @@ struct flb_http_client_response {
size_t data_len;
size_t data_size;
size_t data_size_max;
int buffer_limit_reached; /* Response read failed at the configured limit */
};

/* It hold information about a possible HTTP proxy set by the caller */
Expand Down
114 changes: 114 additions & 0 deletions plugins/out_loki/loki.c
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
#include <fluent-bit/flb_gzip.h>

#include <ctype.h>
#include <errno.h>
#include <sys/stat.h>

#include "loki.h"
Expand Down Expand Up @@ -1892,6 +1893,114 @@ static int collect_tenant_groups(struct flb_loki *ctx,
return 0;
}

static size_t response_body_length(const char *start, const char *end, int base)
{
unsigned long long length;
const char *digits = base == 10 ? "0123456789" : "0123456789abcdefABCDEF";

if (start == end || strspn(start, digits) != (size_t) (end - start)) {
return 0;
}

errno = 0;
length = strtoull(start, NULL, base);
if (errno == ERANGE || length > SIZE_MAX) {
return 0;
}

return (size_t) length;
}

static int oversized_http_400(const struct flb_http_client_response *resp)
{
const char *line = resp->data;
const char *line_end;
const char *p;
const char *value;
const char *value_end;
size_t name_len;
size_t length = 0;
int chunked = FLB_FALSE;
int http_11;

if (!resp->buffer_limit_reached || resp->status != 400 || !resp->headers_end) {
return FLB_FALSE;
}

line_end = strstr(line, "\r\n");
if (!line_end || line_end - line < 13 || line_end > resp->headers_end - 4 ||
memcmp(line, "HTTP/1.", 7) != 0 || (line[7] != '0' && line[7] != '1') ||
memcmp(line + 8, " 400 ", 5) != 0) {
return FLB_FALSE;
}
http_11 = line[7] == '1';
for (p = line + 13; p < line_end; p++) {
if (((unsigned char) *p < 0x20 && *p != '\t') || *p == 0x7f) {
return FLB_FALSE;
}
}

/* Match complete field names and check for conflicting framing. */
for (line = line_end + 2; line < resp->headers_end - 2; line = line_end + 2) {
line_end = strstr(line, "\r\n");
if (!line_end || line_end > resp->headers_end - 4) {
return FLB_FALSE;
}
p = memchr(line, ':', line_end - line);
if (!p || flb_http_header_validate(line, p - line, p + 1, line_end - p - 1) != 0) {
return FLB_FALSE;
}
name_len = p - line;
value = p + 1;
value_end = line_end;
while (value < value_end && (*value == ' ' || *value == '\t')) {
value++;
}
while (value_end > value && (value_end[-1] == ' ' || value_end[-1] == '\t')) {
value_end--;
}

if (name_len == 14 && strncasecmp(line, "Content-Length", name_len) == 0) {
if (length || chunked) {
return FLB_FALSE;
}
length = response_body_length(value, value_end, 10);
if (length == 0) {
return FLB_FALSE;
}
}
else if (name_len == 17 && strncasecmp(line, "Transfer-Encoding", name_len) == 0) {
if (length || chunked || !http_11 || value_end - value != 7 ||
strncasecmp(value, "chunked", 7) != 0) {
return FLB_FALSE;
}
chunked = FLB_TRUE;
}
}

line = resp->headers_end;
if (chunked) {
/* In the full-response read, a consumed chunk advances this cursor. */
if (!resp->chunked_encoding || resp->content_length != -1 ||
resp->chunk_processed_end != line || resp->chunked_trailer_pending) {
return FLB_FALSE;
}
line_end = strstr(line, "\r\n");
if (!line_end) {
return FLB_FALSE;
}
length = response_body_length(line, line_end, 16);
line = line_end + 2;
}
else if (resp->chunked_encoding || resp->content_length <= 0 ||
length != (size_t) resp->content_length) {
return FLB_FALSE;
}

/* Exclude the reserved NUL and compare only body bytes. */
return length > resp->data_size - 1 - (size_t) (line - resp->data);
}

static int send_loki_payload(struct flb_loki *ctx,
flb_sds_t payload,
flb_sds_t tenant_id,
Expand Down Expand Up @@ -2076,6 +2185,11 @@ static int send_loki_payload(struct flb_loki *ctx,
}
}
}
else if (oversized_http_400(&c->resp)) {
flb_plg_error(ctx->ins, "%s:%i, HTTP status=400 Not retrying (response buffer limit reached)",
ctx->tcp_host, ctx->tcp_port);
out_ret = FLB_ERROR;
}
else {
flb_plg_error(ctx->ins, "could not flush records to %s:%i (http_do=%i)",
ctx->tcp_host, ctx->tcp_port, ret);
Expand Down
14 changes: 14 additions & 0 deletions src/flb_http_client.c
Original file line number Diff line number Diff line change
Expand Up @@ -1888,6 +1888,7 @@ int flb_http_do_request(struct flb_http_client *c, size_t *bytes)
size_t bytes_body = 0;
char *tmp;

c->resp.buffer_limit_reached = FLB_FALSE;
if (c->invalid_header) {
return FLB_HTTP_ERROR;
}
Expand Down Expand Up @@ -2015,6 +2016,7 @@ int flb_http_get_response_data(struct flb_http_client *c, size_t bytes_consumed)
int timeout;
int remaining;

c->resp.buffer_limit_reached = FLB_FALSE;
#ifdef __EMSCRIPTEN__
flb_error("[http_client] browser streaming responses are unsupported; use flb_http_do");
return FLB_HTTP_ERROR;
Expand Down Expand Up @@ -2048,6 +2050,15 @@ int flb_http_get_response_data(struct flb_http_client *c, size_t bytes_consumed)
ret = flb_http_buffer_increase(c, FLB_HTTP_DATA_CHUNK,
&out_size);
if (ret == -1) {
if (c->resp.data_size_max != 0 &&
c->resp.data_size >= c->resp.data_size_max) {
now = time(NULL);
c->resp.buffer_limit_reached =
(c->u_conn == NULL || c->u_conn->net_error != ETIMEDOUT) &&
(c->response_timeout <= 0 || now - c->ts_start < c->response_timeout) &&
(c->read_idle_timeout <= 0 || now - c->last_read_ts < c->read_idle_timeout);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}

/*
* We could not allocate more space, let the caller handle
* this.
Expand Down Expand Up @@ -2154,6 +2165,7 @@ int flb_http_do(struct flb_http_client *c, size_t *bytes)
{
int ret;

c->resp.buffer_limit_reached = FLB_FALSE;
if (c->test_mode == FLB_TRUE) {
return flb_http_stub_response(c);
}
Expand Down Expand Up @@ -2220,6 +2232,7 @@ int flb_http_do_with_oauth2(struct flb_http_client *c, size_t *bytes,
{
#ifdef __EMSCRIPTEN__
if (oauth2) {
c->resp.buffer_limit_reached = FLB_FALSE;
flb_error("[http_client] OAuth2 is not supported by the browser transport");
return -1;
}
Expand All @@ -2230,6 +2243,7 @@ int flb_http_do_with_oauth2(struct flb_http_client *c, size_t *bytes,
struct flb_connection *old_conn;
struct flb_upstream *u;

c->resp.buffer_limit_reached = FLB_FALSE;
if (!oauth2 || oauth2->cfg.enabled == FLB_FALSE) {
return flb_http_do(c, bytes);
}
Expand Down
141 changes: 141 additions & 0 deletions tests/integration/scenarios/out_loki/tests/test_out_loki_001.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
import json
import os
from http.server import BaseHTTPRequestHandler, HTTPServer
from pathlib import Path
import tempfile
import threading
import time

import requests
import pytest
Expand Down Expand Up @@ -195,3 +198,141 @@ def test_out_loki_rejects_injected_tenant_header(tenant):
headers = {key.lower(): value for key, value in data_storage["requests"][0]["headers"].items()}
assert headers["x-scope-orgid"] == "safe-tenant"
assert "x-injected-by" not in headers


BAD_REQUEST = b"HTTP/1.1 400 Bad Request\r\n"
LENGTH = BAD_REQUEST + b"Content-Length: "
CHUNKED = BAD_REQUEST + b"Transfer-Encoding: chunked\r\n\r\n"
RESPONSE_CAPACITY = 4096 - 1 # The response buffer reserves a NUL byte.
FIT_LENGTH = RESPONSE_CAPACITY - len(LENGTH + b"0000\r\n\r\n")
FIT_CHUNK = RESPONSE_CAPACITY - len(CHUNKED + b"000\r\n")


def fixed_response(size):
return LENGTH + f"{size}\r\n\r\n".encode() + b"x" * size


def chunked_response(size):
return CHUNKED + f"{size:X}\r\n".encode() + b"x" * size + b"\r\n0\r\n\r\n"


@pytest.mark.parametrize(("wire", "split", "outcome"), [
pytest.param(fixed_response(3), 0, "ordinary", id="ordinary-400"),
pytest.param(fixed_response(8192), 0, "oversized", id="oversized-length"),
pytest.param(fixed_response(FIT_LENGTH - 1), 0, "ordinary", id="length-one-byte-free"),
pytest.param(fixed_response(FIT_LENGTH), RESPONSE_CAPACITY - 1, "exact-fit", id="length-exact-fit"),
pytest.param(fixed_response(FIT_LENGTH + 1), RESPONSE_CAPACITY - 1,
"oversized", id="length-one-byte-over"),
pytest.param(chunked_response(0x2A0B), len(CHUNKED) + 2, "oversized", id="oversized-first-chunk"),
pytest.param(chunked_response(FIT_CHUNK), 0, "retry", id="chunk-body-exact-fit"),
pytest.param(chunked_response(FIT_CHUNK), RESPONSE_CAPACITY - 1,
"retry", id="chunk-body-exact-fit-split"),
pytest.param(chunked_response(FIT_CHUNK + 1), 0, "oversized", id="chunk-body-one-byte-over"),
pytest.param(chunked_response(FIT_CHUNK + 1), RESPONSE_CAPACITY - 1,
"oversized", id="chunk-body-one-byte-over-split"),
pytest.param(CHUNKED + b"2000;foo=bar\r\n" + b"x" * 8192, 0, "retry", id="chunk-extension"),
pytest.param(CHUNKED + b"2000;foo=\r\n" + b"x" * 8192,
0, "retry", id="chunk-extension-missing-value"),
pytest.param(CHUNKED + b"1\r\na\r\n2000\r\n" + b"x" * 8192, 0, "retry", id="previous-chunk"),
pytest.param(CHUNKED + b" 2000\r\n" + b"x" * 8192, 0, "retry", id="chunk-size-leading-space"),
pytest.param(CHUNKED + b"\t2000\r\n" + b"x" * 8192, 0, "retry", id="chunk-size-leading-tab"),
pytest.param(CHUNKED + b"2000 \t\r\n" + b"x" * 8192, 0, "retry", id="chunk-size-whitespace"),
pytest.param(CHUNKED + b"a" * 4096, 0, "retry", id="incomplete-chunk-size"),
pytest.param(CHUNKED + b"0\r\nTrailer: " + b"x" * 4096, 0, "retry", id="incomplete-trailer"),
pytest.param(LENGTH + b"8192\r\nContent-Length: 8192\r\n\r\n" + b"x" * 8192,
0, "retry", id="duplicate-length"),
pytest.param(LENGTH + b"8192\r\nTransfer-Encoding: chunked\r\n\r\n" + b"x" * 8192,
0, "retry", id="conflicting-framing"),
pytest.param(BAD_REQUEST + b"Transfer-Encoding: chunked\r\nTransfer-Encoding: identity\r\n\r\n"
+ b"2000\r\n" + b"x" * 8192, 0, "retry", id="duplicate-transfer-encoding"),
pytest.param(LENGTH + b"8192, 8192\r\n\r\n" + b"x" * 8192, 0, "retry", id="length-list"),
pytest.param(LENGTH + b"+8192\r\n\r\n" + b"x" * 8192, 0, "retry", id="signed-length"),
pytest.param(BAD_REQUEST + b"X-Original-Content-Length: 9000\r\n"
+ fixed_response(8192)[len(BAD_REQUEST):], 0, "retry", id="legacy-length-mismatch"),
pytest.param(BAD_REQUEST + b"X-Original-Content-Length: 8192\r\n\r\n" + b"x" * 8192,
0, "retry", id="close-delimited-with-lookalike-field"),
pytest.param(LENGTH + b"8192\r\nUnfinished: " + b"x" * 4096, 0, "retry", id="incomplete-headers"),
pytest.param(fixed_response(8192).replace(b"400 Bad", b"400XBad", 1),
0, "retry", id="invalid-status-line"),
pytest.param(chunked_response(8192).replace(b"HTTP/1.1", b"HTTP/1.0", 1),
0, "retry", id="http-1.0-chunked"),
pytest.param(fixed_response(8192).replace(b"400 Bad Request", b"503 Unavailable", 1),
0, "retry", id="oversized-503"),
pytest.param(b"HTTP/1.1 429 Too Many Requests\r\nContent-Length: 0\r\n\r\n",
0, "retry", id="ordinary-429"),
pytest.param(b"", 0, "retry", id="connection-closed-without-response"),
])
def test_out_loki_response_buffer_limit(tmp_path, wire, split, outcome):
payloads = []
terminal_markers = {
"ordinary": "HTTP status=400 Not retrying.",
"oversized": "response buffer limit reached",
"retry": "cannot be retried",
}

class LokiReceiver(BaseHTTPRequestHandler):
def do_POST(self):
payloads.append(self.rfile.read(int(self.headers["Content-Length"])))
self.close_connection = True
try:
if outcome == "exact-fit" and len(payloads) > 1:
# Keep the last byte out of the retry so it reaches the same buffer limit.
self.connection.sendall(wire[:-1])
return
if split:
self.connection.sendall(wire[:split])
time.sleep(0.25)
self.connection.sendall(wire[split:])
except (BrokenPipeError, ConnectionResetError):
pass # A capped read closes the connection before draining the response.

with HTTPServer(("127.0.0.1", 0), LokiReceiver) as server:
config = {
"service": {
"flush": 0.2, "grace": 1, "scheduler.base": 1, "scheduler.cap": 1,
"http_server": "on", "http_listen": "127.0.0.1",
"http_port": "${FLUENT_BIT_HTTP_MONITORING_PORT}",
},
"pipeline": {
"inputs": [{"name": "dummy", "samples": 1, "dummy": '{"msg":"synthetic"}'}],
"outputs": [{
"name": "loki", "match": "*", "host": "127.0.0.1", "port": server.server_port,
"buffer_size": "4096", "retry_limit": 1, "net.io_timeout": 2,
}],
},
}
config_path = tmp_path / "loki.yaml"
config_path.write_text(yaml.safe_dump(config), encoding="utf-8")
service = FluentBitTestService(str(config_path))
receiver = threading.Thread(target=server.serve_forever)
receiver.start()
try:
service.start()

log_path = Path(service.flb.log_file)

def has_terminal_outcome():
log = log_path.read_text(encoding="utf-8", errors="replace")
return any(marker in log for marker in terminal_markers.values())

service.wait_for_condition(
has_terminal_outcome, timeout=30 if memory_check_enabled() else 10,
interval=0.1, description="terminal Loki output result",
)
finally:
try:
service.stop()
finally:
server.shutdown()
receiver.join()

log = log_path.read_text(encoding="utf-8", errors="replace")
observed = [result for result, marker in terminal_markers.items() if marker in log]
if outcome == "exact-fit":
assert observed in (["ordinary"], ["retry"]), log
if observed == ["retry"]:
assert log.count("cannot increase buffer") == 2, log
else:
assert observed == [outcome], log
assert len(payloads) == (2 if observed == ["retry"] else 1), (observed, len(payloads), log)
assert all(payload == payloads[0] for payload in payloads)
Loading