Files
moloapp/src/openai/admin/webhooks.cpp
T

244 lines
9.9 KiB
C++
Raw Normal View History

#include "openai/admin/webhooks.h"
#include <algorithm>
#include <cctype>
#include <chrono>
#include "llm/error.h"
#include "openai/admin/caps.h"
#include "openai/admin/validate.h"
#include "security/crypto/Base64.h"
#include "security/crypto/Hmac.h"
#include "security/crypto/SecureRandom.h"
namespace molo::openai::admin {
namespace crypto = security::crypto;
namespace {
constexpr std::size_t kFailureCount = 11;
std::array<std::atomic<std::uint64_t>, kFailureCount> g_failures{};
std::atomic<std::uint64_t> g_accepted{0};
std::string lower(std::string s) {
std::transform(s.begin(), s.end(), s.begin(), [](unsigned char c) { return std::tolower(c); });
return s;
}
[[noreturn]] void bad_secret(const std::string& why) {
Validate::fail("webhook secret unusable: " + why);
}
std::string decode_secret(const std::string& secret) {
if (secret.empty() || secret.size() > AdminCaps::kMaxSecretChars) bad_secret("empty or too long");
static const std::string kPrefix = "whsec_";
if (secret.rfind(kPrefix, 0) != 0) return secret; // raw key bytes, as the SDKs allow
const std::string encoded = secret.substr(kPrefix.size());
std::string decoded;
if (!crypto::Base64::decode(encoded, decoded)) bad_secret("not valid base64");
if (crypto::Base64::encode(decoded) != encoded) bad_secret("base64 is not canonical");
if (decoded.size() < AdminCaps::kMinSecretBytes) bad_secret("decoded key is under 24 bytes");
return decoded;
}
} // namespace
const char* webhook_failure_name(WebhookFailure f) {
switch (f) {
case WebhookFailure::kNone: return "none";
case WebhookFailure::kBadSecret: return "bad_secret";
case WebhookFailure::kBodyTooLarge: return "body_too_large";
case WebhookFailure::kMissingId: return "missing_webhook_id";
case WebhookFailure::kMissingTimestamp: return "missing_webhook_timestamp";
case WebhookFailure::kMissingSignature: return "missing_webhook_signature";
case WebhookFailure::kBadTimestamp: return "bad_timestamp";
case WebhookFailure::kTooOld: return "timestamp_too_old";
case WebhookFailure::kTooNew: return "timestamp_too_new";
case WebhookFailure::kBadSignatureHeader: return "bad_signature_header";
case WebhookFailure::kMismatch: return "signature_mismatch";
}
return "unknown";
}
WebhookHeaders WebhookHeaders::from(const std::map<std::string, std::string>& headers) {
WebhookHeaders out;
for (const auto& [name, value] : headers) {
const std::string n = lower(name);
if (n == "webhook-id") out.id = value;
else if (n == "webhook-timestamp") out.timestamp = value;
else if (n == "webhook-signature") out.signature = value;
}
return out;
}
void WebhookCounters::count(WebhookFailure failure) {
g_failures[static_cast<std::size_t>(failure)].fetch_add(1, std::memory_order_relaxed);
}
std::uint64_t WebhookCounters::value(WebhookFailure failure) {
return g_failures[static_cast<std::size_t>(failure)].load(std::memory_order_relaxed);
}
std::uint64_t WebhookCounters::accepted() { return g_accepted.load(std::memory_order_relaxed); }
void WebhookCounters::count_accepted() { g_accepted.fetch_add(1, std::memory_order_relaxed); }
std::map<std::string, std::uint64_t> WebhookCounters::snapshot() {
std::map<std::string, std::uint64_t> out;
out["accepted"] = accepted();
for (std::size_t i = 1; i < kFailureCount; ++i)
out[webhook_failure_name(static_cast<WebhookFailure>(i))] = value(static_cast<WebhookFailure>(i));
return out;
}
WebhookVerifier::WebhookVerifier(const std::string& secret, std::int64_t tolerance_seconds)
: key_(decode_secret(secret)), tolerance_(tolerance_seconds) {
Validate::range("tolerance_seconds", tolerance_seconds, 0, AdminCaps::kMaxToleranceSeconds);
}
WebhookVerifier::~WebhookVerifier() { crypto::SecureRandom::zeroize(key_); }
std::int64_t WebhookVerifier::system_now() {
return std::chrono::duration_cast<std::chrono::seconds>(
std::chrono::system_clock::now().time_since_epoch())
.count();
}
std::string WebhookVerifier::sign(const std::string& webhook_id, const std::string& timestamp,
const std::string& body) const {
const std::string signed_payload = webhook_id + "." + timestamp + "." + body;
const auto mac = crypto::Hmac::sha256(key_, signed_payload);
return "v1," + crypto::Base64::encode(mac.data(), mac.size());
}
VerifyResult WebhookVerifier::verify(const std::string& body, const WebhookHeaders& h) const {
return verify(body, h, system_now());
}
VerifyResult WebhookVerifier::verify(const std::string& body, const WebhookHeaders& h,
std::int64_t now) const {
auto reject = [](WebhookFailure f, const std::string& why) {
WebhookCounters::count(f);
VerifyResult r;
r.failure = f;
r.reason = why;
return r;
};
if (body.size() > AdminCaps::kMaxWebhookBodyBytes)
return reject(WebhookFailure::kBodyTooLarge, "body is over the byte cap");
if (h.id.empty() || h.id.size() > 256)
return reject(WebhookFailure::kMissingId, "missing webhook-id header");
if (h.timestamp.empty())
return reject(WebhookFailure::kMissingTimestamp, "missing webhook-timestamp header");
if (h.signature.empty())
return reject(WebhookFailure::kMissingSignature, "missing webhook-signature header");
if (h.signature.size() > AdminCaps::kMaxWebhookHeaderChars)
return reject(WebhookFailure::kBadSignatureHeader, "webhook-signature header is too long");
if (h.timestamp.size() > 12 ||
!std::all_of(h.timestamp.begin(), h.timestamp.end(),
[](unsigned char c) { return std::isdigit(c) != 0; }))
return reject(WebhookFailure::kBadTimestamp, "webhook-timestamp is not unix seconds");
const std::int64_t ts = std::stoll(h.timestamp);
if (now - ts > tolerance_) return reject(WebhookFailure::kTooOld, "timestamp is outside the tolerance (old)");
if (ts - now > tolerance_) return reject(WebhookFailure::kTooNew, "timestamp is outside the tolerance (future)");
// Candidate signatures: space separated "v1,<base64>" entries.
std::vector<std::string> candidates;
std::size_t pos = 0;
while (pos < h.signature.size()) {
while (pos < h.signature.size() && std::isspace(static_cast<unsigned char>(h.signature[pos]))) ++pos;
std::size_t end = pos;
while (end < h.signature.size() && !std::isspace(static_cast<unsigned char>(h.signature[end]))) ++end;
if (end > pos) {
const std::string part = h.signature.substr(pos, end - pos);
if (part.rfind("v1,", 0) == 0) candidates.push_back(part.substr(3));
}
pos = end;
}
if (candidates.empty())
return reject(WebhookFailure::kBadSignatureHeader, "no v1 signature in webhook-signature");
if (candidates.size() > AdminCaps::kMaxWebhookSignatures)
return reject(WebhookFailure::kBadSignatureHeader, "too many signatures in webhook-signature");
const std::string signed_payload = h.id + "." + h.timestamp + "." + body;
const auto expected = crypto::Hmac::sha256(key_, signed_payload);
bool match = false;
for (const std::string& c : candidates) {
std::string raw;
if (!crypto::Base64::decode(c, raw) || raw.size() != expected.size()) continue;
match |= crypto::SecureRandom::constant_time_equal(
reinterpret_cast<const std::uint8_t*>(raw.data()), expected.data(), expected.size());
}
if (!match) return reject(WebhookFailure::kMismatch, "signature does not match");
WebhookCounters::count_accepted();
VerifyResult ok;
ok.ok = true;
return ok;
}
void WebhookVerifier::require(const std::string& body, const WebhookHeaders& h,
std::int64_t now) const {
const VerifyResult r = verify(body, h, now);
if (!r.ok) throw llm::ApiError("openai", 401, "INVALID_SIGNATURE", r.reason);
}
WebhookEvent WebhookVerifier::unwrap(const std::string& body, const WebhookHeaders& h,
std::int64_t now) const {
require(body, h, now);
return WebhookEnvelope::parse(body);
}
// ---- endpoint management ----
AdminService::Json WebhookEndpoints::list(std::optional<int> limit, const std::string& after) {
Query q;
if (limit) {
Validate::range("limit", *limit, 1, AdminCaps::kMaxPageLimit);
q.set_int("limit", *limit);
}
if (!after.empty()) q.set("after", after);
return execute(Call::kWebhookEndpointsList, {}, q);
}
AdminService::Json WebhookEndpoints::get(const std::string& endpoint_id) {
return execute(Call::kWebhookEndpointsGet, {endpoint_id});
}
AdminService::Json WebhookEndpoints::create(const WebhookEndpointSpec& spec) {
Json body = spec.to_json(true);
return execute(Call::kWebhookEndpointsCreate, {}, {}, &body);
}
AdminService::Json WebhookEndpoints::update(const std::string& endpoint_id,
const WebhookEndpointSpec& spec) {
Json body = spec.to_json(false);
return execute(Call::kWebhookEndpointsUpdate, {endpoint_id}, {}, &body);
}
AdminService::Json WebhookEndpoints::destroy(const std::string& endpoint_id, bool confirm) {
return execute(Call::kWebhookEndpointsDelete, {endpoint_id}, {}, nullptr, confirm);
}
AdminService::Json WebhookEndpoints::rotate_secret(const std::string& endpoint_id,
bool keep_old_secret_for_24_hours,
bool confirm) {
Json body = Json::object();
body.set("keep_old_secret_active_for_24_hours", Json(keep_old_secret_for_24_hours));
return execute(Call::kWebhookEndpointsRotateSecret, {endpoint_id}, {}, &body, confirm);
}
AdminService::Json WebhookEndpoints::test(const std::string& endpoint_id,
const std::string& event_type) {
if (!WebhookEvents::is_subscribable(event_type))
Validate::fail("event type " + event_type + " cannot be tested");
Json body = Json::object();
body.set("event_type", Json(event_type));
return execute(Call::kWebhookEndpointsTest, {endpoint_id}, {}, &body);
}
AdminService::Json WebhookEndpoints::event_types() {
return execute(Call::kWebhookEventTypesList);
}
} // namespace molo::openai::admin