DEV Community

Cover image for Integrating with Firebase and Pangea's security services
Luke Stahl for Pangea

Posted on • Originally published at pangea.cloud

Integrating with Firebase and Pangea's security services

NOTE: This article originally appeared on the Pangea.

Firebase, similar to the Pangea platform, helps you develop high-quality apps, grow your user base, and focus on providing your users with your unique value proposition. Each feature works independently, and they work even better together. If you are unfamiliar with Firebase and would like to learn more, visit the Firebase site.

In this tutorial, learn how to install and utilize a combination of Pangea provided Firebase Extensions. Firebase Extensions are an easy way to add Pangea services to your Firebase app without the need to write or debug code on your own. Extensions are pre-packaged solutions designed to save development time and quickly deploy Pangea functionality into your applications hosted on Firebase. You provide the configuration parameters, such as authentication tokens, for each extension at install time. All Pangea-provided extensions are open-sourced and built on Firebase and Google Cloud products you already know. Deployment and configuration of each extension are performed in the Firebase console or the Firebase CLI, and once deployed, they require no maintenance.

Each section of this tutorial will focus on a specific Pangea service and demonstrate how to install and utilize the associated Firebase Extension. After completing the first section, Configure a Starter Project, you can follow the tutorial sequentially to implement the complete use case or skip to each section relevant to you. As the Pangea platform's capabilities increase with the addition of new services, this tutorial will also evolve to highlight the new functionality. You can refer to this multi-part series at any time to learn about new Pangea services and how they may help secure an application hosted on Firebase.

Configure a Starter Application

Overview

In this section, you will familiarize yourself with Firebase and the services it offers, such as the NoSQL document database, Cloud Firestore, that lets you easily store, sync, and query data. You will also configure Cloud Storage which is designed to help you quickly and easily store and serve user-generated content, such as photos and videos. In the subsequent sections, you will utilize Pangea-provided Firebase Extensions to secure your app. For a complete list of the Firebase services available to app builders, visit the Firebase Products page.

Firebase services are designed to reduce development time by streamlining commonly performed tasks when developing applications; similarly, Pangea can be thought of as a stack-agnostic security framework. Regardless of what technologies you use to build your apps, Pangea is designed to alleviate your team from the burden of compliance.

Note
If you already have a Firebase project you'd like to secure with Pangea, you can skip this section and install the extensions covered in the subsequent sections to your existing project.

Prerequisites

  • A free Firebase account
  • Node.js (version 14.16.1 or higher) and npm installed on your machine.

Create the sample project

Step 1: From the Firebase Console, select Create a project:

Image description

Step 2: Select a project name and follow the setup wizard:

Image description

Take a moment to explore the console and services available. It contains four service categories, Build, Release & Monitor, Analytics, and Engage.

Configure a Firestore Database

Next, to create a Cloud Firestore database to store and sync data between your client-side and server-side apps, perform the following steps:

Step 1: From the Project Overview left-hand menu, expand the Build section, and select Firestore Database.

Image description

Step 2: Click the Create database button.

Image description

Follow the configuration wizard to select an initial security mode and region to deploy the database.

Image description

Note
Pangea recommends selecting the Start in production mode, even for a test project.

Step 3: You should now have a fully configured database that you can add collections and documents to. You will learn how to install extensions to listen and react to document changes in later sections of this tutorial.

Image description

Configure Cloud Storage

Next, to create a Cloud Storage container to store files such as images and videos, perform the following steps:

Step 1: From the Project Overview left-hand menu, expand the Build section, select Storage, and click the Get started button.

Image description

Step 2: Follow the configuration wizard to select an initial security mode and region to deploy the Storage service.

Image description

Note
Pangea recommends selecting the Start in production mode, even for a test project.

Step 3: You should now have a fully configured Storage container that you can upload files to. You will learn how to install extensions to listen and react to upload events in the next section of this tutorial.

Image description

Configure Authentication

To enabled authentication and allow users to create accounts to access your application services, perform the following steps:

Step 1: From the Project Overview left-hand menu, expand the Build section, select Authentication, and click the Get started button.

Image description

Step 2: From the Sign-in providers section, under the Native providers column, select Email/Password.

Image description

Step 3: Enable the Email/Password provider and click Save button.

Image description

Configure Cloud Functions, billing profile, and your local environment.

To enable Cloud Functions to host and run serverless code, you'll need to upgrade your Firebase account to a Blaze tier Pay as you go plan. To do so, perform the following steps:

Step 1: From the Project Overview left-hand menu, expand the Build section, select Functions, and click the Upgrade Project button.

Image description

Step 2: To upgrade, click the Continue button and follow the instructions. You will be redirected to the Set up your billing profile section of Google Cloud Platform (GCP) and asked to complete a billing profile.

Image description

Note
You will only be charged if to you exceed the usage allotted by the free tier. Visit the Firebase Pricing page for details.

Step 3: After setting up your GCP billing profile, you will be redirected back to the Firebase Console. From the left-hand menu, expand the Build section, select Functions, and click the Get started button.

Image description

Step 4: Follow the instructions in the Set up Functions wizard. First, to install the Firebase tools run the following command:

npm install -g firebase-tools
Enter fullscreen mode Exit fullscreen mode

Image description

To link your firebase account to the command-line tools installed, run:

firebase login
Enter fullscreen mode Exit fullscreen mode

Follow the instructions presented by the login command, then when presented with the Sign in screen in a browser window, use your Google Account to log in and grant the Firebase CLI access to the permissions it needs.

Image description

Note
If the browser window is not automatically presented, copy and paste the URL provided by the firebase login command into a new browser window or tab.

Then, to initialize your Firebase project for local development, create a folder for your project, set the current directory to the folder created, and run the following command:

firebase init
Enter fullscreen mode Exit fullscreen mode

Image description

You will be guided through the configuration process with a series of questions.

Note
You will be prompted to select which Firebase services you'd like to configure. These will vary depending on your desired use case but for the purpose of this tutorial, make sure to at least select Firestore, Functions, and Storage.

Here is an example output:

local-machine:~/Development/YourFirstFirebaseProject Firebase init

     ######## #### ########  ######## ########     ###     ######  ########
     ##        ##  ##     ## ##       ##     ##  ##   ##  ##       ##
     ######    ##  ########  ######   ########  #########  ######  ######
     ##        ##  ##    ##  ##       ##     ## ##     ##       ## ##
     ##       #### ##     ## ######## ########  ##     ##  ######  ########

You're about to initialize a Firebase project in this directory:

  /Users/Development/YourFirstFirebaseProject

? Which Firebase features do you want to set up for this directory? Press Space to select features, then Enter to c
onfirm your choices. Firestore: Configure security rules and indexes files for Firestore, Functions: Configure a Cl
oud Functions directory and its files, Storage: Configure a security rules file for Cloud Storage, Emulators: Set u
p local emulators for Firebase products

=== Project Setup

First, let's associate this project directory with a Firebase project.
You can create multiple project aliases by running firebase use --add,
but for now we'll just set up a default project.

? Please select an option: Use an existing project
? Select a default Firebase project for this directory: yourfirstfirebaseproject (YourFirstFirebaseProject)
i  Using project yourfirstfirebaseproject (YourFirstFirebaseProject)

=== Firestore Setup

Firestore Security Rules allow you to define how and when to allow
requests. You can keep these rules in your project directory
and publish them with firebase deploy.

? What file should be used for Firestore Rules? firestore.rules

Firestore indexes allow you to perform complex queries while
maintaining performance that scales with the size of the result
set. You can keep index definitions in your project directory
and publish them with firebase deploy.

? What file should be used for Firestore indexes? firestore.indexes.json

=== Functions Setup
Let's create a new codebase for your functions.
A directory corresponding to the codebase will be created in your project
with sample code pre-configured.

See https://firebase.google.com/docs/functions/organize-functions for
more information on organizing your functions using codebases.

Functions can be deployed with firebase deploy.

? What language would you like to use to write Cloud Functions? TypeScript
? Do you want to use ESLint to catch probable bugs and enforce style? Yes
✔  Wrote functions/package.json
✔  Wrote functions/.eslintrc.js
✔  Wrote functions/tsconfig.json
✔  Wrote functions/tsconfig.dev.json
✔  Wrote functions/src/index.ts
✔  Wrote functions/.gitignore
? Do you want to install dependencies with npm now? Yes
npm WARN EBADENGINE Unsupported engine {
npm WARN EBADENGINE   package: undefined,
npm WARN EBADENGINE   required: { node: '16' },
npm WARN EBADENGINE   current: { node: 'v19.2.0', npm: '8.19.3' }
npm WARN EBADENGINE }

added 410 packages, and audited 411 packages in 52s

89 packages are looking for funding
  run `npm fund` for details

2 vulnerabilities (1 moderate, 1 high)

To address all issues (including breaking changes), run:
  npm audit fix --force

Run `npm audit` for details.

=== Storage Setup

Firebase Storage Security Rules allow you to define how and when to allow
uploads and downloads. You can keep these rules in your project directory
and publish them with firebase deploy.

? What file should be used for Storage Rules? storage.rules
✔  Wrote storage.rules

=== Emulators Setup
? Which Firebase emulators do you want to set up? Press Space to select emulators, then Enter to confirm your choic
es. Authentication Emulator, Functions Emulator, Firestore Emulator, Storage Emulator, Eventarc Emulator
? Which port do you want to use for the auth emulator? 9099
? Which port do you want to use for the functions emulator? 5001
? Which port do you want to use for the firestore emulator? 8080
? Which port do you want to use for the storage emulator? 9199
? Which port do you want to use for the eventarc emulator? 9299
? Would you like to enable the Emulator UI? Yes
? Which port do you want to use for the Emulator UI (leave empty to use any available port)?
? Would you like to download the emulators now? Yes
i  ui: downloading ui-v1.11.2.zip...

i  Writing configuration info to firebase.json...
i  Writing project information to .firebaserc...
i  Writing gitignore file to .gitignore...

✔  Firebase initialization complete!
Enter fullscreen mode Exit fullscreen mode

Navigate back to the browser with the Firebase console and click the Finish button of the Set up Functions dialog. The second command, firebase deploy shown in that dialog, is not required since you do not yet have functions to deploy. However, you now have the Cloud Functions service configured and the Waiting for your first deploy message displayed, as shown below.

Image description

The Pangea Extensions you will install in the following few sections of this tutorial are actually pre-packaged Cloud Functions provided by Pangea that you can deploy and authorize to run in your Firebase environment. All the Pangea Extensions are open source and available for you to reference, modify, and improve. You can visit our Github Repository to view or download the code. To learn how to quickly leverage the power of Pangea's security services without needing to write or debug code proceed to the next section.

Install the Known Malware Detection Extension

Overview

Firebase Cloud Storage is designed to store and serve user-generated content with ease as you prototype and scale your application. But what happens when a user uploads a malicious file? The Pangea Known Malware Detection Extension can be configured to automatically check files uploaded by users against a database of 25 million known malicious files, and if deemed dangerous, it can be naturalized by packaging it into a password protected gzip container.

In this section, you will learn how to install, configure, and test the Extension and leverage the Pangea File Intel Service without writing a single line of code.

Prerequisites

Install and configure the Extension

Step 1: Click the Known Malware Detection install link, and select the Firebase project you'd like to deploy the Extension to:

Image description

Step 2: Accept the Early Access acknowledgement by clicking the Next button:

Image description

Step 3: Review the billing and usage details, and tap the Next button. If you have not done so already, you'll be presented with the option to upgrade your Firebase account to a pay-as-you-go plan, you can do so by clicking the Upgrade project to continue button and following the instructions:

Image description

Note
If you upgrade your billing plan, you will be redirected to the Set up your billing profile section of Google Cloud Platform (GCP). After setting up your billing profile, you may need to restart the Extension install by clicking the install and repeating Step 1 and Step 2.

Step 4: Review the APIs and the resources that will be created by this Extension. If any required Firebase services are not yet enabled, tap the Enable button next to each required service and then click the Next button.

Image description

Step 5: In the Review access granted to this extension section, grant the extension permission to Storage and Secrets Manager by clicking the Next button.

Image description

Note
The Storage Admin permission will be used to store gzip formatted files that contain and neutralize malicious files uploaded to your bucket, and the Secret Manager Secret Accessor permission is required to store your Pangea Auth Token, and optional password for any gzip files created.

Step 5: In the final step, Configure extension, of the install process, you'll be asked to provide a few parameters, some of which are optional. The first two are what region you want to deploy the Extension and where your Pangea services are deployed, respectively. The Extension should be deployed as close to your Firebase Cloud Storage, so ideally, the same region you used when you configured it. The Pangea service base Domain and Auth Token can be copied from the Pangea Console > File Intel Overview page. The Pangea Auth Token and optional password to protect the gzip container should be stored in Google Secret Manager. To do so, just click the Create secret button next to each input field after entering their respective value.

The rest of the parameters are either optional or have default values to dictate which buckets you want to monitor, which paths to include or ignore, and whether to delete or keep a malicious file when it is detected.

Note
You can use the default values for now and reconfigure your Extension later.

Image description

You can also configure how much memory to allocate to your function; neutralizing large files may require more memory.

Check the Enable events box and select the completed event. This will allow your Firebase application to listen to and react when malicious files are uploaded.

Note
In this tutorial's next section, Add Secure Audit Logging, you will configure the Pangea Secure Audit Log Extension to log events emitted from this Known Malware Detection Extension.

To complete the installation, click the Install extension button.

Image description

It may take Firebase 3-5 minutes to deploy your Extension. When it completes, you should see it listed under the Extensions section of your Firebase Console.

Image description

Test the Extension

Instead of testing the Known Malware Detection Extensions with a real malicious file or virus, you can use a file developed by the European Institute for Computer Antivirus Research (EICAR) known as the EICAR Anti-Virus test file. It was developed to test the response of computer anti-virus (AV) programs. Instead of using real malware, which could cause real damage, this test file allows you to test anti-virus software without having to use a real computer virus. To do so, do the following:

Step 1: To create the EICAR antivirus test file, create a file with this string:

5O!P%@AP[4\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*

Note
You can also download the test file directly from: eicar.com

Step 2: Using the Firebase Project Overview left-hand menu, expand the Build section, and select Storage.

Image description

Step 3: Click the Upload file button, and select the eicar-test-file.com file you downloaded in the previous step. After a few seconds, you will notice that the file was moved into a .zip file under the path you configured; we used /malicious as the default. If you also chose the default extension configuration, the complete path will be /malicious/eicar-test-file_com.zip. You can download this file, inspect its contents, or send it to an incident response team for analysis.

Note
You may need to refresh the browser to load the updated paths.

Image description

Note
You can also try to upload a non-malicious file and note that the Extension does not process it.

Add Secure Audit Log to security-critical app events

Overview

In this section, learn how to install, configure and invoke the Pangea Secure Audit Log Extension to leverage the Secure Audit Log . Once installed, the Extension will automatically log security-critical events emitted by Firebase and other Pangea Extensions. You will also learn how to log your custom app events by recording them in a Firebase Firestore Document. Using the Pangea Console Log Viewer you can cryptographically verify that records have not been modified, inserted, or deleted.

When your application utilizes Pangea's tamperproof logging service, log hashes are automatically published to an immutable public ledger or blockchain. Doing so provides irrefutable evidence of what events occurred in an application without exposing the logs' contents publicly. With the Secure Audit Log Extension, you can deliver the power of the blockchain to your users without writing a single line of code.

Prerequisites

Install and configure the Extension

Step 1: Click the Secure Audit Logging Extension install link, and select the Firebase project you'd like to deploy the Extension to:

Image description

Step 2: Accept the Early Access acknowledgement by clicking the Next button:

Image description

Step 3: Review the billing and usage details, and tap the Next button. If you have not done so already, you'll be presented with the option to upgrade your Firebase account to a pay-as-you-go plan, and you can do so by clicking the Upgrade project to continue button and following the instructions:

Image description

Note
If upgrading your billing plan, you will be redirected to the Set up your billing profile section of Google Cloud Platform (GCP). After setting up your billing profile, you may need to restart the Extension install by clicking the install and repeating Step 1 and Step 2.

Step 4: Review the APIs and the resources that this Extension will create. If any required Firebase services are not yet enabled, tap the Enable button next to each required service and then click the Next button.

Image description

Note
_The Extension declares several functions to create Secure Audit Log entries:

fslog - listens for changes made to a Firestore collection. You can invoke this Extension to log custom events by writing to a document in a specified collection.

onmaliciousfiledetected - will be automatically invoked by the Known Malware Detection Extension installed in the previous section of this tutorial if you enabled the completed event.

onusercreated - will be automatically invoked when a user is created.

onuserdeleted - will be automatically invoked when a user is created._

_onlogevent - listens for custom log events you can emit from your application code.
_

Step 5: In the Review access granted to this extension section, grant the extension permission to Firestore and Secrets Manager by clicking the Next button.

Image description

Note
The Cloud datastore User permission will be used to read and write the responses of the Pangea Secure Audit Log service to a Firestore document. The Secret Manager Secret Accessor permission is required to store your Pangea Auth Token.

Step 6: In the final step, Configure extension, of the install process, you'll be asked to provide a few parameters, some of which are optional. The first two and what region you want to deploy the Extension and where your Pangea services are deployed, respectively. The Extension should be deployed as close to your Firebase Cloud Firestore, so ideally, the same region you used when you configured it. The Pangea service base Domain and Auth Token can be copied from Secure Audit Log Overview page of the Pangea Console. The Pangea Auth Token should be stored in Google Secret Manager. To do so, click the Create secret button next to its input field after entering the token value.

The Collection path and Input field name are the Firestore paths you want to write custom events to, and the Response output field name is the path to which the response of each request will be written to by the Extension.

Note
You can use the default values for now and reconfigure your Extension later.

Image description

To complete the installation, click the Install extension button.

It may take Firebase 3-5 minutes to deploy your Extension. When it completes, you should see it listed under the Extensions section of your Firebase Console.

Image description

That's it! You now have Secure Audit Logging enabled in your Firebase app. Events emitted from other Pangea Extensions will automatically be recorded.

Test automatic logging of events from other Pangea Extensions

To test events automatically logged by the Known Malware Detection Extension, upload another malicious file to Cloud Storage. To do so, refer to the Test the Extension portion of the previous section, 2. Detect malicious Files uploaded to Cloud Storage of this tutorial and perform Step 1, Step 2, and Step 3.

Note
If you have not done so already, make sure to delete the test file from your previous test.

Then, to view the event, navigate to the Pangea Console Log Viewer of the Pangea Console. You should see the event similar to:

Image description

Test automatic logging of Firebase Authentication events

This Secure Audit Logging Extension listens for and automatically logs when a new Firebase user is created or deleted. To test and view these events, perform the following steps:

Step 1: From Firebase Console, expand the Build category, select Authentication from the left-hand menu, and click the Add user button.

Image description

Step 2: Enter a Email and Password for your test user and click the Add user button in the Add an Email/Password user dialog box.

Note
You do not need to use a valid email address. You will delete this user account in the next step.

Image description

Step 3: Expand the user options using the three-dot options menu button on the right-hand side of the user row you created in the previous step. Click the Delete account option, and when the Delete account dialog box is presented, confirm the delete by clicking the Delete button.

Image description

Step 4: Then, to view the User created and User deleted events, navigate back to the Pangea Console Log Viewer of the Pangea Console. You should see the event similar to:

Image description

Test logging custom events by writing to Firestore

When you installed the Secure Audit Logging Extension, you configured it to listen to changes to a specific Document in your application's Firestore database. To record your custom application events, such as user login attempts, registrations, or object access attempts, you can invoke the Pangea Secure Audit Log service by simply writing to the Document. In this section, you will test this functionality using the Firebase Console user interface. To do so, perform the following steps:

Step 1: From Firebase Console, expand the Build category and select Firestore Database from the left-hand menu.

Image description

Step 2: Select the Start collection option from the Panel View, and because you used the default collection name when installing the Secure Audit Logging Extension, enter 'audit' as the Collection ID and click the Next button.

Note
The collection names are case-sensitive. Use all lowercase letters in the Collection ID field.

Image description

Step 3: To add the Document to the Collection, click the Auto-ID button to generate an ID for the Document; then again, because you used the default configuration parameters when you installed the Extension, enter 'log' as the Field value and set the Type to map.

Image description

A document with an auto-generated Document ID and single Field of type map should look similar to this:

Image description

Step 4: You can now map each of the Pangea Secure Audit Log API parameters to a Field of the 'log' map. Add the following Field : Value pairs, each of Type string:

message : Hello, World!
action  : test
status  : complete
source  : firestore
target  : audit-log-ext
actor   : firebase-console
Enter fullscreen mode Exit fullscreen mode

Then, to create the Document and trigger Secure Audit Log Service, click the Save button.

Image description

In a few moments, you should see a response field containing the Pangea service response added to the Document as a pier to the log field you created.

Image description

Then, to view the event, navigate back to the Pangea Console Log Viewer of the Pangea Console. You can expand the log entry by clicking on it to reveal the custom metadata fields. You should see an entry similar to the one below:

Image description

The Secure Audit Logging Extension will be invoked by any write operation to the Document it is configured to observe. The Cloud Firestore Panel view is a great way to test the Extension by quickly creating and editing Firestore documents, but you may want to record auditable events from your application code. With the Secure Audit Logging Extension installed, you can do so from anywhere in your application that can write to Firestore.

Here is a quick example of how to create the same Document programmatically:

import {getFirestore} from "firebase-admin/firestore";

getFirestore().collection("audit").add({
  log: {
    message: "Hello, World!",
    action: "test",
    status: "complete",
    source: "firestore",
    target: "audit-log-ext",
    actor: "firebase-console",
  },
});
Enter fullscreen mode Exit fullscreen mode

You can also send custom events to the extension using EventArc. Here is an example:

import {getEventarc} from "firebase-admin/eventarc";

getEventarc().channel().publish({
  type: "firebase.extensions.pangea-audit-log.v1.log",
  data: {
    message: "Hello, World!",
    action: "test",
    status: "complete",
    source: "target",
    target: "audit-log-ext",
    actor: "firebase-console",
  },
});
Enter fullscreen mode Exit fullscreen mode

Top comments (0)