Jblew / firebase-functions-rate-limiter

Js/ts library that allows you to set per-time, per-user or per-anything limits for calling Firebase cloud functions
MIT License
100 stars 15 forks source link

Firebase functions rate limiter

npm Code coverage License PRs Welcome

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

Key features:

Installation

$ npm install --save firebase-functions-rate-limiter

Then:

import FirebaseFunctionsRateLimiter from "firebase-functions-rate-limiter";
// or
const { FirebaseFunctionsRateLimiter } = require("firebase-functions-rate-limiter");

Usage

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 while limiter.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" };
});

Step-by-step

#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
    }

Configuration

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)
};

Choose backend:

const limiter = FirebaseFunctionsRateLimiter.withRealtimeDbBackend(configuration, database)
// or
const limiter = FirebaseFunctionsRateLimiter.withFirestoreBackend(configuration, firestore)
// or, for functions unit testing convenience:
const limiter = FirebaseFunctionsRateLimiter.mock()

Methods

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.

Firebase configuration

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.

Need help?

Would like to help?

Warmly welcomed:


Made with ❤️ by Jędrzej Lewandowski.