
Research
Malicious npm Packages Impersonate Flashbots SDKs, Targeting Ethereum Wallet Credentials
Four npm packages disguised as cryptographic tools steal developer credentials and send them to attacker-controlled Telegram infrastructure.
firebase-functions-rate-limiter
Advanced tools
JS/TS library that allows you to set per - time, per - user or per - anything limits for calling Firebase cloud functions
Q: How to limit rate of firebase function calls?
A: Use firebase-functions-rate-limiter
Mission: limit number of calls per specified period of time
$ npm install --save firebase-functions-rate-limiter
Then:
import FirebaseFunctionsRateLimiter from "firebase-functions-rate-limiter";
// or
const { FirebaseFunctionsRateLimiter } = require("firebase-functions-rate-limiter");
Example 1: limit calls for everyone:
import * as admin from "firebase-admin";
import * as functions from "firebase-functions";
import { FirebaseFunctionsRateLimiter } from "firebase-functions-rate-limiter";
admin.initializeApp(functions.config().firebase);
const database = admin.database();
const limiter = FirebaseFunctionsRateLimiter.withRealtimeDbBackend(
{
name: "rate_limiter_collection",
maxCalls: 2,
periodSeconds: 15,
},
database,
);
exports.testRateLimiter =
functions.https.onRequest(async (req, res) => {
await limiter.rejectOnQuotaExceededOrRecordUsage(); // will throw HttpsException with proper warning
res.send("Function called");
});
You can use two functions:
limiter.rejectOnQuotaExceededOrRecordUsage(qualifier?)
will throw an functions.https.HttpsException when limit is exceeded whilelimiter.isQuotaExceededOrRecordUsage(qualifier?)
gives you the ability to choose how to handle the situation.
Example 2: limit calls for each user separately (function called directly - please refer firebase docs on this topic):
import * as admin from "firebase-admin";
import * as functions from "firebase-functions";
import { FirebaseFunctionsRateLimiter } from "firebase-functions-rate-limiter";
admin.initializeApp(functions.config().firebase);
const database = admin.database();
const perUserlimiter = FirebaseFunctionsRateLimiter.withRealtimeDbBackend(
{
name: "per_user_limiter",
maxCalls: 2,
periodSeconds: 15,
},
database,
);
exports.authenticatedFunction =
functions.https.onCall(async (data, context) => {
if (!context.auth || !context.auth.uid) {
throw new functions.https.HttpsError(
"failed-precondition",
"Please authenticate",
);
}
const uidQualifier = "u_" + context.auth.uid;
const isQuotaExceeded = await perUserlimiter.isQuotaExceededOrRecordUsage(uidQualifier);
if (isQuotaExceeded) {
throw new functions.https.HttpsError(
"failed-precondition",
"Call quota exceeded for this user. Try again later",
);
}
return { result: "Function called" };
});
#1 Initialize admin app and get Realtime database object
admin.initializeApp(functions.config().firebase);
const database = admin.database();
#2 Create limiter object outside of the function scope and pass the configuration and Database object. Configuration options are listed below.
const someLimiter = FirebaseFunctionsRateLimiter.withRealtimeDbBackend(
{
name: "limiter_some",
maxCalls: 10,
periodSeconds: 60,
},
database,
);
#3 Inside the function call isQuotaExceededOrRecordUsage. This is an async function so not forget about await! The function will check if the limit was exceeded. If limit was not exceeded it will record this usage and return true. Otherwise, write will be only called if there are usage records that are older than the specified period and are about to being cleared.
exports.testRateLimiter =
functions.https.onRequest(async (req, res) => {
const quotaExceeded = await limiter.isQuotaExceededOrRecordUsage();
if (quotaExceeded) {
// respond with error
} else {
// continue
}
#3 with qualifier. Optionally you can pass a qualifier to the function. A qualifier is a string that identifies a separate type of call. If you pass a qualifier, the limit will be recorded per each distinct qualifier and won't sum up.
exports.testRateLimiter =
functions.https.onRequest(async (req, res) => {
const qualifier = "user_1";
const quotaExceeded = await limiter.isQuotaExceededOrRecordUsage(qualifier);
if (quotaExceeded) {
// respond with error
} else {
// continue
}
const configuration = {
name: // a collection with this name will be created
periodSeconds: // the length of test period in seconds
maxCalls: // number of maximum allowed calls in the period
debug: // boolean (default false)
};
const limiter = FirebaseFunctionsRateLimiter.withRealtimeDbBackend(configuration, database)
// or
const limiter = FirebaseFunctionsRateLimiter.withFirestoreBackend(configuration, firestore)
// or, for functions unit testing convenience:
const limiter = FirebaseFunctionsRateLimiter.mock()
isQuotaExceededOrRecordUsage(qualifier?: string)
— Checks if quota was exceed. If not — it records the call time in the appropriate backend.
rejectOnQuotaExceededOrRecordUsage(qualifier?: string, errorFactory?: (configuration) => Error)
— Checks if quota was exceed. If not — it records the call time in the appropriate backend and is rejected with functions.https.HttpsException. This particular exception can be caught when calling the firebase function directly (see https://firebase.google.com/docs/functions/callable). When errorFactory is provided, it is used to obtain error that is thrown in case of exceeded limit.
isQuotaAlreadyExceeded(qualifier?: string)
— Checks if quota was exceed, but does not record a usage. If you use this, you must call isQuotaExceededOrRecordUsage() to record the usage.
getConfiguration()
— Returns this rate limiter configuration.
— deprecated: renamed to isQuotaExceededOrRecordUsageisQuotaExceeded(qualifier?: string)
— deprecated: renamed to rejectOnQuotaExceededOrRecordUsagerejectOnQuotaExceeded(qualifier?: string)
Why is there no recordUsage()
method?** This library uses a document-per-qualifier data model which requires a read call before the update call. Read-and-update is performed inside an atomic transaction in both backend. It would not be concurrency-safe if the read-and-update transaction was split into separate calls.
There is no configuration needed in the firebase. This library does not do document search, so you do not need indexes. Also, functions are executed in the firebase admin environment, so you do not have to specify any rules.
Warmly welcomed:
Made with ❤️ by Jędrzej Lewandowski.
FAQs
JS/TS library that allows you to set per - time, per - user or per - anything limits for calling Firebase cloud functions
The npm package firebase-functions-rate-limiter receives a total of 2,982 weekly downloads. As such, firebase-functions-rate-limiter popularity was classified as popular.
We found that firebase-functions-rate-limiter demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Research
Four npm packages disguised as cryptographic tools steal developer credentials and send them to attacker-controlled Telegram infrastructure.
Security News
Ruby maintainers from Bundler and rbenv teams are building rv to bring Python uv's speed and unified tooling approach to Ruby development.
Security News
Following last week’s supply chain attack, Nx published findings on the GitHub Actions exploit and moved npm publishing to Trusted Publishers.