Skip to content

Commit

Permalink
Add a simple rate limiter to schema requests to allow them to be unau…
Browse files Browse the repository at this point in the history
…thenticated
  • Loading branch information
lindkvis committed Nov 20, 2023
1 parent 6ba569e commit bfd3fa1
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 1 deletion.
38 changes: 37 additions & 1 deletion RestInterface/cafRestSchemaService.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,39 @@
#include <vector>

using namespace caffa::rpc;
using namespace std::chrono_literals;

constexpr std::chrono::seconds RATE_LIMITER_TIME_PERIOD = 1s;
constexpr size_t RATE_LIMITER_MAX_REQUESTS = 5;

std::mutex RestSchemaService::s_requestMutex;
std::list<std::chrono::steady_clock::time_point> RestSchemaService::s_requestTimes;

bool RestSchemaService::refuseDueToTimeLimiter()
{
std::scoped_lock lock( s_requestMutex );

auto now = std::chrono::steady_clock::now();

std::list<std::chrono::steady_clock::time_point> recentRequests;
for ( auto requestTime : s_requestTimes )
{
if ( now - requestTime < RATE_LIMITER_TIME_PERIOD )
{
recentRequests.push_back( requestTime );
}
}

s_requestTimes.swap( recentRequests );

if ( s_requestTimes.size() >= RATE_LIMITER_MAX_REQUESTS )
{
return true;
}

s_requestTimes.push_back( now );
return false;
}

RestSchemaService::ServiceResponse RestSchemaService::perform( http::verb verb,
const std::list<std::string>& path,
Expand Down Expand Up @@ -61,7 +94,10 @@ RestSchemaService::ServiceResponse RestSchemaService::perform( http::verb

if ( !session && RestServerApplication::instance()->requiresValidSession() )
{
return std::make_tuple( http::status::forbidden, "No session provided", nullptr );
if ( refuseDueToTimeLimiter() )
{
return std::make_tuple( http::status::too_many_requests, "Too many unauthenticated schema requests", nullptr );
}
}

if ( path.empty() )
Expand Down
9 changes: 9 additions & 0 deletions RestInterface/cafRestSchemaService.h
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@

#include <nlohmann/json.hpp>

#include <chrono>
#include <list>
#include <mutex>
#include <string>
#include <utility>

Expand Down Expand Up @@ -55,6 +58,12 @@ class RestSchemaService : public RestServiceInterface
static ServiceResponse getFieldSchema( const caffa::ObjectHandle* object, const std::string& fieldName );

static ServiceResponse getAllSchemas();

private:
static bool refuseDueToTimeLimiter();

static std::list<std::chrono::steady_clock::time_point> s_requestTimes;
static std::mutex s_requestMutex;
};

} // namespace caffa::rpc

0 comments on commit bfd3fa1

Please sign in to comment.