Merge netapp-kv-http: HTTP application layer (NetworkedApplications)
This commit is contained in:
commit
fd763e4feb
4 files changed
+707
-1
No files matched your search
@@ -9,7 +9,10 @@ set(CMAKE_CXX_EXTENSIONS OFF)
|
||||
|
||||
find_package(Void CONFIG REQUIRED COMPONENTS Runtime)
|
||||
|
||||
add_library(networked_kv STATIC src/application.cpp src/memory_store.cpp)
|
||||
add_library(networked_kv STATIC
|
||||
src/application.cpp
|
||||
src/http_api.cpp
|
||||
src/memory_store.cpp)
|
||||
target_include_directories(networked_kv PUBLIC include)
|
||||
target_link_libraries(networked_kv PUBLIC Void::Runtime)
|
||||
|
||||
@@ -19,6 +22,10 @@ target_link_libraries(networked_kv_test PRIVATE networked_kv)
|
||||
add_executable(networked_kv_domain_test tests/domain_test.cpp)
|
||||
target_link_libraries(networked_kv_domain_test PRIVATE networked_kv)
|
||||
|
||||
add_executable(networked_kv_http_test tests/http_api_test.cpp)
|
||||
target_link_libraries(networked_kv_http_test PRIVATE networked_kv)
|
||||
|
||||
enable_testing()
|
||||
add_test(NAME networked_kv_lifecycle COMMAND networked_kv_test)
|
||||
add_test(NAME networked_kv_domain COMMAND networked_kv_domain_test)
|
||||
add_test(NAME networked_kv_http COMMAND networked_kv_http_test)
|
||||
@@ -0,0 +1,84 @@
|
||||
#pragma once
|
||||
|
||||
#include "networked_kv/domain.hpp"
|
||||
|
||||
#include <Void/Functional/Result.hpp>
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <map>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
namespace NetworkedKv
|
||||
{
|
||||
struct HttpRequest {
|
||||
std::string method;
|
||||
std::string target;
|
||||
std::map<std::string, std::string, std::less<>> headers;
|
||||
std::string body;
|
||||
|
||||
[[nodiscard]] std::optional<std::string_view>
|
||||
header(std::string_view name) const;
|
||||
};
|
||||
|
||||
struct HttpResponse {
|
||||
int status{200};
|
||||
std::map<std::string, std::string, std::less<>> headers;
|
||||
std::string body;
|
||||
};
|
||||
|
||||
struct ApiConfig {
|
||||
std::string bearer_token;
|
||||
std::size_t max_body_bytes{1024ULL * 1024ULL};
|
||||
std::size_t max_scan_limit{1000};
|
||||
};
|
||||
|
||||
struct ApiMetrics {
|
||||
std::uint64_t requests{0};
|
||||
std::uint64_t unauthorized{0};
|
||||
std::uint64_t client_errors{0};
|
||||
std::uint64_t server_errors{0};
|
||||
std::uint64_t bytes_in{0};
|
||||
std::uint64_t bytes_out{0};
|
||||
};
|
||||
|
||||
/// Transport-agnostic HTTP application layer for the key-value service.
|
||||
///
|
||||
/// Net owns parsing and framing; this maps an already-parsed request to the
|
||||
/// KV domain, enforces bearer auth on the data plane, and exposes bounded
|
||||
/// admin views that never dump credentials or mutate data.
|
||||
class KvApi
|
||||
{
|
||||
public:
|
||||
|
||||
KvApi(KvStore& store, ApiConfig config);
|
||||
|
||||
[[nodiscard]] HttpResponse handle(const HttpRequest& request);
|
||||
|
||||
[[nodiscard]] HttpResponse admin(const HttpRequest& request) const;
|
||||
|
||||
void set_ready(bool ready) noexcept { m_ready = ready; }
|
||||
|
||||
[[nodiscard]] ApiMetrics metrics() const noexcept { return m_metrics; }
|
||||
|
||||
private:
|
||||
|
||||
[[nodiscard]] bool authorized(const HttpRequest& request) const;
|
||||
[[nodiscard]] HttpResponse
|
||||
kv_get(std::string_view key, const HttpRequest& request);
|
||||
[[nodiscard]] HttpResponse
|
||||
kv_put(std::string_view key, const HttpRequest& request);
|
||||
[[nodiscard]] HttpResponse
|
||||
kv_delete(std::string_view key, const HttpRequest& request);
|
||||
[[nodiscard]] HttpResponse
|
||||
kv_scan(const HttpRequest& request);
|
||||
void note(const HttpResponse& response);
|
||||
|
||||
KvStore& m_store;
|
||||
ApiConfig m_config;
|
||||
bool m_ready{true};
|
||||
ApiMetrics m_metrics;
|
||||
};
|
||||
} // namespace NetworkedKv
|
||||
@@ -0,0 +1,440 @@
|
||||
#include "networked_kv/http_api.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <charconv>
|
||||
#include <format>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
|
||||
namespace NetworkedKv
|
||||
{
|
||||
namespace
|
||||
{
|
||||
constexpr std::string_view kJsonType{"application/json"};
|
||||
constexpr std::string_view kTextType{"text/plain; charset=utf-8"};
|
||||
constexpr std::string_view kKvPrefix{"/v1/kv/"};
|
||||
|
||||
[[nodiscard]] bool iequals(std::string_view lhs,
|
||||
std::string_view rhs) noexcept
|
||||
{
|
||||
if (lhs.size() != rhs.size()) {
|
||||
return false;
|
||||
}
|
||||
for (std::size_t i = 0; i < lhs.size(); ++i) {
|
||||
const char a = lhs[i] >= 'A' && lhs[i] <= 'Z'
|
||||
? static_cast<char>(lhs[i] + 32)
|
||||
: lhs[i];
|
||||
const char b = rhs[i] >= 'A' && rhs[i] <= 'Z'
|
||||
? static_cast<char>(rhs[i] + 32)
|
||||
: rhs[i];
|
||||
if (a != b) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
[[nodiscard]] std::string_view path_of(std::string_view target) noexcept
|
||||
{
|
||||
const auto query = target.find('?');
|
||||
return target.substr(0, query);
|
||||
}
|
||||
|
||||
[[nodiscard]] std::string_view query_of(std::string_view target) noexcept
|
||||
{
|
||||
const auto query = target.find('?');
|
||||
return query == std::string_view::npos ? std::string_view{}
|
||||
: target.substr(query + 1);
|
||||
}
|
||||
|
||||
[[nodiscard]] std::optional<std::string_view>
|
||||
query_param(std::string_view query, std::string_view name) noexcept
|
||||
{
|
||||
while (!query.empty()) {
|
||||
const auto amp = query.find('&');
|
||||
const auto part = query.substr(0, amp);
|
||||
const auto eq = part.find('=');
|
||||
if (eq != std::string_view::npos &&
|
||||
part.substr(0, eq) == name) {
|
||||
return part.substr(eq + 1);
|
||||
}
|
||||
if (amp == std::string_view::npos) {
|
||||
break;
|
||||
}
|
||||
query.remove_prefix(amp + 1);
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
[[nodiscard]] bool constant_time_equal(std::string_view lhs,
|
||||
std::string_view rhs) noexcept
|
||||
{
|
||||
if (lhs.size() != rhs.size()) {
|
||||
return false;
|
||||
}
|
||||
unsigned int diff = 0;
|
||||
for (std::size_t i = 0; i < lhs.size(); ++i) {
|
||||
diff |= static_cast<unsigned int>(
|
||||
static_cast<unsigned char>(lhs[i]) ^
|
||||
static_cast<unsigned char>(rhs[i]));
|
||||
}
|
||||
return diff == 0;
|
||||
}
|
||||
|
||||
[[nodiscard]] std::string json_escape(std::string_view input,
|
||||
std::size_t max)
|
||||
{
|
||||
std::string out;
|
||||
out.reserve(std::min(input.size(), max) + 8);
|
||||
for (const char ch : input) {
|
||||
if (out.size() >= max) {
|
||||
break;
|
||||
}
|
||||
const auto byte = static_cast<unsigned char>(ch);
|
||||
switch (ch) {
|
||||
case '"': out += "\\\""; break;
|
||||
case '\\': out += "\\\\"; break;
|
||||
case '\n': out += "\\n"; break;
|
||||
case '\r': out += "\\r"; break;
|
||||
case '\t': out += "\\t"; break;
|
||||
default:
|
||||
if (byte < 0x20) {
|
||||
out += std::format("\\u{:04x}", byte);
|
||||
} else {
|
||||
out += ch;
|
||||
}
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
[[nodiscard]] int status_for(const Void::Result::Error& error) noexcept
|
||||
{
|
||||
using Kind = Void::Result::ErrorKind;
|
||||
switch (error.kind()) {
|
||||
case Kind::invalid_argument: return 400;
|
||||
case Kind::not_found: return 404;
|
||||
case Kind::conflict: return 409;
|
||||
case Kind::exhausted: return 429;
|
||||
case Kind::overloaded: return 503;
|
||||
case Kind::cancelled: return 499;
|
||||
case Kind::timeout: return 504;
|
||||
case Kind::unsupported: return 501;
|
||||
default: return 500;
|
||||
}
|
||||
}
|
||||
|
||||
[[nodiscard]] HttpResponse error_response(int status,
|
||||
std::string message)
|
||||
{
|
||||
HttpResponse response;
|
||||
response.status = status;
|
||||
response.headers["content-type"] = std::string{kJsonType};
|
||||
response.body = "{\"error\":\"" + json_escape(message, 512) + "\"}";
|
||||
return response;
|
||||
}
|
||||
|
||||
[[nodiscard]] HttpResponse text_response(int status, std::string body)
|
||||
{
|
||||
HttpResponse response;
|
||||
response.status = status;
|
||||
response.headers["content-type"] = std::string{kTextType};
|
||||
response.body = std::move(body);
|
||||
return response;
|
||||
}
|
||||
|
||||
[[nodiscard]] std::optional<Version>
|
||||
parse_etag(std::string_view value) noexcept
|
||||
{
|
||||
if (value.size() >= 2 && value.front() == '"' &&
|
||||
value.back() == '"') {
|
||||
value = value.substr(1, value.size() - 2);
|
||||
}
|
||||
Version version = 0;
|
||||
const auto parsed = std::from_chars(
|
||||
value.data(), value.data() + value.size(), version);
|
||||
if (parsed.ec != std::errc{} ||
|
||||
parsed.ptr != value.data() + value.size()) {
|
||||
return std::nullopt;
|
||||
}
|
||||
return version;
|
||||
}
|
||||
|
||||
[[nodiscard]] std::string etag(Version version)
|
||||
{
|
||||
return "\"" + std::to_string(version) + "\"";
|
||||
}
|
||||
} // namespace
|
||||
|
||||
std::optional<std::string_view>
|
||||
HttpRequest::header(std::string_view name) const
|
||||
{
|
||||
for (const auto& [key, value] : headers) {
|
||||
if (iequals(key, name)) {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
KvApi::KvApi(KvStore& store, ApiConfig config)
|
||||
: m_store(store)
|
||||
, m_config(std::move(config))
|
||||
{
|
||||
}
|
||||
|
||||
bool KvApi::authorized(const HttpRequest& request) const
|
||||
{
|
||||
// Fail closed: an empty configured token authorizes nothing.
|
||||
if (m_config.bearer_token.empty()) {
|
||||
return false;
|
||||
}
|
||||
const auto header = request.header("authorization");
|
||||
if (!header) {
|
||||
return false;
|
||||
}
|
||||
constexpr std::string_view scheme{"bearer "};
|
||||
if (header->size() < scheme.size() ||
|
||||
!iequals(header->substr(0, scheme.size()), scheme)) {
|
||||
return false;
|
||||
}
|
||||
return constant_time_equal(header->substr(scheme.size()),
|
||||
m_config.bearer_token);
|
||||
}
|
||||
|
||||
void KvApi::note(const HttpResponse& response)
|
||||
{
|
||||
m_metrics.bytes_out += response.body.size();
|
||||
if (response.status >= 500) {
|
||||
++m_metrics.server_errors;
|
||||
} else if (response.status >= 400) {
|
||||
++m_metrics.client_errors;
|
||||
}
|
||||
}
|
||||
|
||||
HttpResponse KvApi::handle(const HttpRequest& request)
|
||||
{
|
||||
++m_metrics.requests;
|
||||
m_metrics.bytes_in += request.target.size() + request.body.size();
|
||||
|
||||
if (request.body.size() > m_config.max_body_bytes) {
|
||||
HttpResponse response = error_response(413, "request body too large");
|
||||
note(response);
|
||||
return response;
|
||||
}
|
||||
|
||||
const auto path = path_of(request.target);
|
||||
HttpResponse response;
|
||||
if (path.starts_with(kKvPrefix) || path == "/v1/scan") {
|
||||
if (!authorized(request)) {
|
||||
++m_metrics.unauthorized;
|
||||
response = error_response(401, "missing or invalid bearer token");
|
||||
} else if (path == "/v1/scan") {
|
||||
response = request.method == "GET"
|
||||
? kv_scan(request)
|
||||
: error_response(405, "method not allowed");
|
||||
} else {
|
||||
const auto key = path.substr(kKvPrefix.size());
|
||||
if (key.empty()) {
|
||||
response = error_response(400, "key required");
|
||||
} else if (request.method == "GET") {
|
||||
response = kv_get(key, request);
|
||||
} else if (request.method == "PUT") {
|
||||
response = kv_put(key, request);
|
||||
} else if (request.method == "DELETE") {
|
||||
response = kv_delete(key, request);
|
||||
} else {
|
||||
response = error_response(405, "method not allowed");
|
||||
}
|
||||
}
|
||||
} else {
|
||||
response = error_response(404, "not found");
|
||||
}
|
||||
note(response);
|
||||
return response;
|
||||
}
|
||||
|
||||
HttpResponse KvApi::kv_get(std::string_view key, const HttpRequest&)
|
||||
{
|
||||
auto got = m_store.get(key);
|
||||
if (!got) {
|
||||
return error_response(status_for(got.error()),
|
||||
got.error().message());
|
||||
}
|
||||
if (!got->has_value()) {
|
||||
return error_response(404, "not found");
|
||||
}
|
||||
HttpResponse response;
|
||||
response.status = 200;
|
||||
response.headers["content-type"] = "application/octet-stream";
|
||||
response.headers["etag"] = etag((*got)->version);
|
||||
response.headers["cache-control"] = "no-store";
|
||||
response.body = (*got)->value;
|
||||
return response;
|
||||
}
|
||||
|
||||
HttpResponse KvApi::kv_put(std::string_view key, const HttpRequest& request)
|
||||
{
|
||||
const auto request_id = request.header("x-request-id");
|
||||
if (!request_id || request_id->empty()) {
|
||||
return error_response(428, "x-request-id required");
|
||||
}
|
||||
Precondition precondition;
|
||||
if (const auto none = request.header("if-none-match");
|
||||
none && *none == "*") {
|
||||
precondition = Precondition::absent();
|
||||
} else if (const auto match = request.header("if-match")) {
|
||||
const auto version = parse_etag(*match);
|
||||
if (!version) {
|
||||
return error_response(400, "invalid if-match");
|
||||
}
|
||||
precondition = Precondition::at_version(*version);
|
||||
} else {
|
||||
return error_response(428,
|
||||
"if-none-match or if-match required");
|
||||
}
|
||||
|
||||
auto result = m_store.put(key, request.body, precondition,
|
||||
RequestId{std::string{*request_id}});
|
||||
if (!result) {
|
||||
return error_response(status_for(result.error()),
|
||||
result.error().message());
|
||||
}
|
||||
switch (result->outcome) {
|
||||
case WriteOutcome::Applied: {
|
||||
HttpResponse response = text_response(200, "applied");
|
||||
response.headers["etag"] = etag(result->version);
|
||||
return response;
|
||||
}
|
||||
case WriteOutcome::Conflict:
|
||||
return error_response(412, "version precondition failed");
|
||||
case WriteOutcome::NotFound:
|
||||
return error_response(404, "not found");
|
||||
case WriteOutcome::Unknown:
|
||||
return error_response(503, "commit outcome unknown");
|
||||
}
|
||||
return error_response(500, "unreachable");
|
||||
}
|
||||
|
||||
HttpResponse KvApi::kv_delete(std::string_view key,
|
||||
const HttpRequest& request)
|
||||
{
|
||||
const auto request_id = request.header("x-request-id");
|
||||
if (!request_id || request_id->empty()) {
|
||||
return error_response(428, "x-request-id required");
|
||||
}
|
||||
const auto match = request.header("if-match");
|
||||
if (!match) {
|
||||
return error_response(428, "if-match required");
|
||||
}
|
||||
const auto version = parse_etag(*match);
|
||||
if (!version) {
|
||||
return error_response(400, "invalid if-match");
|
||||
}
|
||||
|
||||
auto result = m_store.erase(key, Precondition::at_version(*version),
|
||||
RequestId{std::string{*request_id}});
|
||||
if (!result) {
|
||||
return error_response(status_for(result.error()),
|
||||
result.error().message());
|
||||
}
|
||||
switch (result->outcome) {
|
||||
case WriteOutcome::Applied: {
|
||||
HttpResponse response;
|
||||
response.status = 204;
|
||||
return response;
|
||||
}
|
||||
case WriteOutcome::Conflict:
|
||||
return error_response(412, "version precondition failed");
|
||||
case WriteOutcome::NotFound:
|
||||
return error_response(404, "not found");
|
||||
case WriteOutcome::Unknown:
|
||||
return error_response(503, "commit outcome unknown");
|
||||
}
|
||||
return error_response(500, "unreachable");
|
||||
}
|
||||
|
||||
HttpResponse KvApi::kv_scan(const HttpRequest& request)
|
||||
{
|
||||
const auto query = query_of(request.target);
|
||||
const auto cursor = query_param(query, "cursor");
|
||||
std::size_t limit = 0;
|
||||
if (const auto raw = query_param(query, "limit")) {
|
||||
std::size_t parsed = 0;
|
||||
const auto result = std::from_chars(
|
||||
raw->data(), raw->data() + raw->size(), parsed);
|
||||
if (result.ec != std::errc{} ||
|
||||
result.ptr != raw->data() + raw->size() || parsed == 0) {
|
||||
return error_response(400, "invalid limit");
|
||||
}
|
||||
limit = std::min(parsed, m_config.max_scan_limit);
|
||||
}
|
||||
|
||||
auto page = m_store.scan(cursor ? std::optional<std::string_view>{*cursor}
|
||||
: std::nullopt,
|
||||
limit);
|
||||
if (!page) {
|
||||
return error_response(status_for(page.error()),
|
||||
page.error().message());
|
||||
}
|
||||
|
||||
std::string body = "{\"items\":[";
|
||||
for (std::size_t i = 0; i < page->items.size(); ++i) {
|
||||
const auto& item = page->items[i];
|
||||
if (i != 0) {
|
||||
body += ',';
|
||||
}
|
||||
body += "{\"key\":\"" + json_escape(item.key, 1024) +
|
||||
"\",\"version\":" + std::to_string(item.entry.version) +
|
||||
",\"value\":\"" + json_escape(item.entry.value, 64 * 1024) +
|
||||
"\"}";
|
||||
}
|
||||
body += "],\"next_cursor\":";
|
||||
if (page->next_cursor) {
|
||||
body += "\"" + json_escape(*page->next_cursor, 1024) + "\"";
|
||||
} else {
|
||||
body += "null";
|
||||
}
|
||||
body += '}';
|
||||
|
||||
HttpResponse response;
|
||||
response.status = 200;
|
||||
response.headers["content-type"] = std::string{kJsonType};
|
||||
response.headers["cache-control"] = "no-store";
|
||||
response.body = std::move(body);
|
||||
return response;
|
||||
}
|
||||
|
||||
HttpResponse KvApi::admin(const HttpRequest& request) const
|
||||
{
|
||||
const auto path = path_of(request.target);
|
||||
if (request.method != "GET") {
|
||||
return error_response(405, "method not allowed");
|
||||
}
|
||||
if (path == "/live") {
|
||||
return text_response(200, "ok");
|
||||
}
|
||||
if (path == "/ready") {
|
||||
return m_ready ? text_response(200, "ready")
|
||||
: text_response(503, "not ready");
|
||||
}
|
||||
if (path == "/metrics") {
|
||||
std::string body;
|
||||
body += "# bounded application counters\n";
|
||||
body += "networked_kv_requests_total " +
|
||||
std::to_string(m_metrics.requests) + "\n";
|
||||
body += "networked_kv_unauthorized_total " +
|
||||
std::to_string(m_metrics.unauthorized) + "\n";
|
||||
body += "networked_kv_client_errors_total " +
|
||||
std::to_string(m_metrics.client_errors) + "\n";
|
||||
body += "networked_kv_server_errors_total " +
|
||||
std::to_string(m_metrics.server_errors) + "\n";
|
||||
body += "networked_kv_bytes_in_total " +
|
||||
std::to_string(m_metrics.bytes_in) + "\n";
|
||||
body += "networked_kv_bytes_out_total " +
|
||||
std::to_string(m_metrics.bytes_out) + "\n";
|
||||
return text_response(200, std::move(body));
|
||||
}
|
||||
return error_response(404, "not found");
|
||||
}
|
||||
} // namespace NetworkedKv
|
||||
@@ -0,0 +1,175 @@
|
||||
#include "networked_kv/http_api.hpp"
|
||||
|
||||
#include <cassert>
|
||||
#include <cstdio>
|
||||
#include <string>
|
||||
|
||||
namespace
|
||||
{
|
||||
using namespace NetworkedKv;
|
||||
|
||||
HttpRequest make_request(std::string method, std::string target,
|
||||
std::string body = {})
|
||||
{
|
||||
HttpRequest request;
|
||||
request.method = std::move(method);
|
||||
request.target = std::move(target);
|
||||
request.body = std::move(body);
|
||||
return request;
|
||||
}
|
||||
|
||||
HttpRequest authed(HttpRequest request)
|
||||
{
|
||||
request.headers["authorization"] = "Bearer secret";
|
||||
return request;
|
||||
}
|
||||
|
||||
void bearer_auth_is_required()
|
||||
{
|
||||
MemoryKvStore store;
|
||||
KvApi api{store, ApiConfig{.bearer_token = "secret"}};
|
||||
|
||||
assert(api.handle(make_request("GET", "/v1/kv/a")).status == 401);
|
||||
|
||||
auto wrong = make_request("GET", "/v1/kv/a");
|
||||
wrong.headers["authorization"] = "Bearer wrong";
|
||||
assert(api.handle(wrong).status == 401);
|
||||
assert(api.metrics().unauthorized == 2);
|
||||
|
||||
// Fail closed when no token is configured.
|
||||
KvApi unconfigured{store, ApiConfig{}};
|
||||
assert(unconfigured.handle(authed(make_request("GET", "/v1/kv/a")))
|
||||
.status == 401);
|
||||
}
|
||||
|
||||
void kv_lifecycle_over_http()
|
||||
{
|
||||
MemoryKvStore store;
|
||||
KvApi api{store, ApiConfig{.bearer_token = "secret"}};
|
||||
|
||||
auto put = authed(make_request("PUT", "/v1/kv/a", "one"));
|
||||
put.headers["x-request-id"] = "r1";
|
||||
put.headers["if-none-match"] = "*";
|
||||
auto created = api.handle(put);
|
||||
assert(created.status == 200);
|
||||
assert(created.headers.at("etag") == "\"1\"");
|
||||
|
||||
auto get = authed(make_request("GET", "/v1/kv/a"));
|
||||
auto got = api.handle(get);
|
||||
assert(got.status == 200);
|
||||
assert(got.body == "one");
|
||||
assert(got.headers.at("etag") == "\"1\"");
|
||||
|
||||
auto stale = authed(make_request("PUT", "/v1/kv/a", "two"));
|
||||
stale.headers["x-request-id"] = "r2";
|
||||
stale.headers["if-match"] = "\"9\"";
|
||||
assert(api.handle(stale).status == 412);
|
||||
|
||||
// Replaying the same request id returns the recorded outcome and does
|
||||
// not apply the mutation again.
|
||||
auto replay = authed(make_request("PUT", "/v1/kv/a", "ignored"));
|
||||
replay.headers["x-request-id"] = "r1";
|
||||
replay.headers["if-none-match"] = "*";
|
||||
auto replayed = api.handle(replay);
|
||||
assert(replayed.status == 200);
|
||||
assert(replayed.headers.at("etag") == "\"1\"");
|
||||
assert(api.handle(get).body == "one");
|
||||
|
||||
auto delete_stale = authed(make_request("DELETE", "/v1/kv/a"));
|
||||
delete_stale.headers["x-request-id"] = "r3";
|
||||
delete_stale.headers["if-match"] = "\"9\"";
|
||||
assert(api.handle(delete_stale).status == 412);
|
||||
|
||||
auto remove = authed(make_request("DELETE", "/v1/kv/a"));
|
||||
remove.headers["x-request-id"] = "r4";
|
||||
remove.headers["if-match"] = "\"1\"";
|
||||
assert(api.handle(remove).status == 204);
|
||||
assert(api.handle(get).status == 404);
|
||||
}
|
||||
|
||||
void request_validation()
|
||||
{
|
||||
MemoryKvStore store;
|
||||
KvApi api{store, ApiConfig{.bearer_token = "secret",
|
||||
.max_body_bytes = 4}};
|
||||
|
||||
auto oversized = authed(make_request("PUT", "/v1/kv/a", "12345"));
|
||||
oversized.headers["x-request-id"] = "r";
|
||||
oversized.headers["if-none-match"] = "*";
|
||||
assert(api.handle(oversized).status == 413);
|
||||
|
||||
auto no_id = authed(make_request("PUT", "/v1/kv/a", "x"));
|
||||
no_id.headers["if-none-match"] = "*";
|
||||
assert(api.handle(no_id).status == 428);
|
||||
|
||||
auto no_precondition = authed(make_request("PUT", "/v1/kv/a", "x"));
|
||||
no_precondition.headers["x-request-id"] = "r";
|
||||
assert(api.handle(no_precondition).status == 428);
|
||||
|
||||
assert(api.handle(authed(make_request("POST", "/v1/kv/a")))
|
||||
.status == 405);
|
||||
assert(api.handle(authed(make_request("GET", "/v1/nope"))).status ==
|
||||
404);
|
||||
}
|
||||
|
||||
void scan_is_bounded()
|
||||
{
|
||||
MemoryKvStore store{Limits{.max_scan_page = 2}};
|
||||
KvApi api{store, ApiConfig{.bearer_token = "secret",
|
||||
.max_scan_limit = 2}};
|
||||
for (int i = 0; i < 5; ++i) {
|
||||
auto put = authed(make_request(
|
||||
"PUT", "/v1/kv/" + std::string(1, static_cast<char>('a' + i)),
|
||||
"v"));
|
||||
put.headers["x-request-id"] = "s" + std::to_string(i);
|
||||
put.headers["if-none-match"] = "*";
|
||||
assert(api.handle(put).status == 200);
|
||||
}
|
||||
|
||||
auto page = api.handle(authed(make_request("GET", "/v1/scan")));
|
||||
assert(page.status == 200);
|
||||
// Two items retained, and a cursor is offered for the rest.
|
||||
std::size_t keys = 0;
|
||||
for (std::size_t pos = 0;
|
||||
(pos = page.body.find("\"key\":", pos)) != std::string::npos;
|
||||
pos += 6) {
|
||||
++keys;
|
||||
}
|
||||
assert(keys == 2);
|
||||
assert(page.body.find("\"next_cursor\":null") == std::string::npos);
|
||||
|
||||
assert(api.handle(authed(make_request("GET", "/v1/scan?limit=0")))
|
||||
.status == 400);
|
||||
}
|
||||
|
||||
void admin_views_are_bounded()
|
||||
{
|
||||
MemoryKvStore store;
|
||||
KvApi api{store, ApiConfig{.bearer_token = "secret"}};
|
||||
assert(api.admin(make_request("GET", "/live")).status == 200);
|
||||
assert(api.admin(make_request("GET", "/ready")).status == 200);
|
||||
api.set_ready(false);
|
||||
assert(api.admin(make_request("GET", "/ready")).status == 503);
|
||||
|
||||
(void)api.handle(authed(make_request("GET", "/v1/kv/a")));
|
||||
auto metrics = api.admin(make_request("GET", "/metrics"));
|
||||
assert(metrics.status == 200);
|
||||
assert(metrics.body.find("networked_kv_requests_total") !=
|
||||
std::string::npos);
|
||||
// No credential material in the admin output.
|
||||
assert(metrics.body.find("secret") == std::string::npos);
|
||||
assert(api.admin(make_request("POST", "/live")).status == 405);
|
||||
assert(api.admin(make_request("GET", "/unknown")).status == 404);
|
||||
}
|
||||
} // namespace
|
||||
|
||||
int main()
|
||||
{
|
||||
bearer_auth_is_required();
|
||||
kv_lifecycle_over_http();
|
||||
request_validation();
|
||||
scan_is_bounded();
|
||||
admin_views_are_bounded();
|
||||
std::puts("networked-kv http api ok");
|
||||
return 0;
|
||||
}
|
||||
Reference in new issue
Block a user