The task is to make CRUD operations in Firestore after I make an API call to Cloud Function, which later should trigger a Firestore function to get a set of items in Cards collection.
Here are some rules:
There should be no user authentication needed
It shouldn't need to have a service account with granted permissions
The purpose behind the "rules" is to legitimate operations happening in Cloud Functions as it was an authorized admin itself (Because they are deployed to Firebase safe environment anyways right?). Since the plan is to host the project as a Cloud Function, we should be required to have firebase-admin SDK.
For so far, I tried to implement the same with firebase-functions but it only worked if the rule was not restricted publicly being as:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /Cards/{card}{
allow write,read: if false;
}
}
}
Since this works, but the rule is "insecure" I'd like to do these operations only as "admin" would through Cloud Functions. Here is some code that returns an empty array of documents, even though I have data in it viewable from web GUI.
import { getFirestore } from "firebase-admin/firestore";
import * as admin from "firebase-admin";
const GetCard = (cardID: string)=> {
require("../../path-to-the-file.json");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
});
getFirestore()
.collection("Cards")
.get()
.then((cardsSnapshot) => {
cardsSnapshot.forEach((card) => {
console.log("card from collection: ", JSON.stringify(card.data()));
});
});
};
EDIT: the reason why I decided to use adminSDK even though Cloud Functions don't need it was the error I was getting:
Error adding document: [FirebaseError: Missing or insufficient permissions.] {
> code: 'permission-denied',
> customData: undefined,
> toString: [Function (anonymous)]
> }
After running this code:
import { initializeApp } from "firebase/app";
import { collection, getDocs, getFirestore } from "firebase/firestore";
const GetCard = (cardID: string): Promise<Card> => {
const firebaseConfig = {...CONFIGS...};
const app = initializeApp(firebaseConfig);
const db = getFirestore(app);
getDocs(collection(db, "Cards"))
.then((querySnapshot) => {
querySnapshot.forEach((doc) => {
console.log(`${doc.id} => ${doc.data()}`);
});
})
.catch((e) => {
console.error("Error adding document: ", e);
});
};
... without admin SDK using Firebase Functions
Actually Cloud Functions do use the Admin SDK. As such they totally bypass the Firestore security rules: they have full access rights (write & read) to all the collections of your database.
So if I correctly understand, by using Cloud Functions you will fulfill you needs.
Just to be complete, there is a service account for the Cloud Function but it is automatically set-up by the platform, so it is transparent for you.
Related
I am trying to access my db upon http request.
in the api builder from google i use node.js 16 as a runtime.
I tried running this code:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firestore);
const firestoreDB = admin.firestore()
exports.helloWorld = functions.https.onRequest((request, response) => {
response.send("Hello from Firebase Cloud Functions!");
console.log("function triggered")
});
exports.createUser = functions.firestore.document('Users/asddsa')
.onCreate((snap, context) => {
const newValue = snap.data();
if (snap.data() === null) return null;
const uid = context.params.userId
let notificationCollectionRef = firestoreDB.collection('Users').doc(uid).collection('Notifications')
return notificationCollectionRef.add({
notification: 'Hello Notification',
notificationType: 'Welcome'
}).then(ref => {
return console.log('notification successful', ref.id)
})
});
But I cant even deploy it, it just states that "deployment failed".
Now this is usually when there is a typo in the code. But I am guessing that I didnt set up the connection to the firestore properley. (I never gave it a password or anything)
I assumed that as it is inside the same project, the connection would work either way, but maybe I am wrong?
How do I set up the connection to create the user and not have the deployment fail?
The instructions for Initial setup to configure and set up your Cloud Functions for Firebase project. you can check the Firebase documentation.
You can check the details in Cloud firestore trigger. Which describes Event triggers where you can trigger a function to fire any time a new document is created in a collection by using an onCreate(). This function calls createUser every time a new user profile is added.
Also You can have a look at Github link to create the user.
I try to use Firebase in my application. The frontend logs the user in using the Web SDK, without any backend. Later, I would like to call some backend APIs. For this reason, I pass the idToken to the backend and try to validate the user as described in the Firebase docs.
When I do the above flow locally using the Firebase Emulator everything works as expected.
When I switch off the Emulator the idToken validation fails with
{
errorInfo: {
code: 'auth/argument-error',
message: 'Firebase ID token has invalid signature. See https://firebase.google.com/docs/auth/admin/verify-id-tokens for details on how to retrieve an ID token.'
},
codePrefix: 'auth'
}
I created a Google hosted Firebase function to check if I can get the idToken validated there. The above setup works when the validation happens within the Google infrastructure.
Based on the above, I think the issue is in my FirebaseApp setup in the API. What that issue might be?
This is my setup.
I define 3 environment variables:
FIREBASE_DB_URL=https://<project-id>.firebaseio.com
FIREBASE_PROJECT_ID=<project-id>
GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json
I checked and cat $GOOGLE_APPLICATION_CREDENTIALS prints the correct file.
I initialize Firebase in the API with
import admin from "firebase-admin";
if(admin.apps.length == 0) {
admin.initializeApp({
credential: admin.credential.applicationDefault(),
databaseURL: process.env.FIREBASE_DB_URL,
projectId: process.env.FIREBASE_PROJECT_ID,
});
console.log('Firebase initialized')
} else {
console.warn('Firebase already initialized')
}
and this is the validating code
import { DecodedIdToken } from 'firebase-admin/lib/auth/token-verifier';
import { getAuth } from 'firebase-admin/auth';
import './initializeFirebase';
export default async function needsLoggedInUser(idToken: string): Promise<DecodedIdToken|false> {
try {
return await getAuth().verifyIdToken(idToken)
} catch(err) {
console.error(err)
return false
}
}
I use the above in a NextJS API code as
import { NextApiRequest, NextApiResponse } from 'next'
import { getDatabase } from 'firebase-admin/database';
import 'services/backend/initializeFirebase';
import needsLoggedInUser from 'services/backend/needsLoggedInUser';
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
// As an admin, the app has access to read and write all data, regardless of Security Rules
const decodedToken = await needsLoggedInUser(req.body.user)
if(!decodedToken) {
return res.status(403).send("403 Forbidden")
}
/// ... rest of the API
}
I am writing a backend service to manage my tenants in gcp. Specifically, I’d like to be able to create/delete and list tenants, on my node server.
The Firebase admin-sdk should enable me to do so. When I try to run it I get this error:
Credential implementation provided to initializeApp() via the "credential" property failed to fetch a valid Google OAuth2 access token with the following error: "Error fetching access token: Error while making request: getaddrinfo ENOTFOUND metadata.google.internal. Error code: ENOTFOUND".
I followed this documentation to set up install the admin sdk. (tried windows and linux, using an environment variable)
I used this documentation (Getting an existing tenant)
This is my code:
var admin = require('firebase-admin');
var app = admin.initializeApp({
credential: admin.credential.applicationDefault(),
projectId: 'myProject'
});
admin.auth().tenantManager().getTenant("myTenant")
.then((tenant) => {
console.log(tenant.toJSON());
})
.catch((error) => {
// Handle error.
console.log(error.message)
});
const someOtherStuff = () =>...
module.exports = {
someOtherStuff
}
Edit: I am running this code locally on a node server with Express. I am using a Windows computer and a Linux computer. The result is the same on both systems.
I was able to work around the problem by changing the initialization. Instead of using environment variables, I used the service account key file directly, as described here
Some sample code of how I use it:
var admin = require('firebase-admin');
var {getAuth} = require('firebase-admin/auth');
var serviceAccount = require('/path/to/serviceAccountKey.json');
// Initialize the default app using seriveAccount instead of environment variables
var app = admin.initializeApp({
credential: admin.credential.cert(serviceAccount)
});
const createTenant = async (tenantName) => getAuth(app).tenantManager().createTenant({
displayName: tenantName,
emailSignInConfig: {
enabled: true,
passwordRequired: true, // Email link sign-in enabled.
}
}).then((createdTenant) => {
return createdTenant.toJSON();
}).catch((error) => {
console.log("tenant could not be created. " + error.message);
});
//some other stuff...
module.exports = {
createTenant,
someOtherStuff,
}
I am trying to create a new vm using Nodejs client libraries of GCP, I followed the below link,
https://googleapis.dev/nodejs/compute/latest/VM.html#create
and below is my code
const Compute = require('#google-cloud/compute');
const {auth} = require('google-auth-library');
const compute = new Compute();
var cred = "<<<credential json content as string>>>";
auth.scopes = ['https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/compute'];
auth.jsonContent = JSON.parse(cred);
const config = {
machineType: 'n1-standard-1',
disks: [ {
boot: true,
initializeParams: { sourceImage: '<<<image url>>>' }
} ],
networkInterfaces: [ { network: 'global/networks/default' } ],
tags: [ { items: [ 'debian-server', 'http-server' ] } ],
auth: auth,
};
async function main() {
// [START gce_create_vm]
async function createVM() {
const zone = compute.zone('us-central1-c');
const vm = zone.vm('vm-name');
await vm.create(config).then(function(data) {
const vm = data[0];
const operation = data[1];
const apiResponse = data[2];
});
console.log(vm);
console.log('Virtual machine created!');
}
createVM().catch(function (err) {
console.log(err);
});
// [END gce_create_vm]
}
main();
when i run this, the error I am getting is
Error: Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information.
at GoogleAuth.getApplicationDefaultAsync (D:\Click to deploy\src\c2dNodeGCP\node_modules\google-auth-library\build\src\auth\googleauth.js:155:19)
at processTicksAndRejections (internal/process/task_queues.js:97:5)
at async GoogleAuth.getClient (D:\Click to deploy\src\c2dNodeGCP\node_modules\google-auth-library\build\src\auth\googleauth.js:487:17)
at async GoogleAuth.authorizeRequest (D:\Click to deploy\src\c2dNodeGCP\node_modules\google-auth-library\build\src\auth\googleauth.js:528:24)
My scenario is to take the service account credential from string variable rather than from env var or some other thing.
I can see that it is trying to take the default credential which is not there in my case.
I was able to achieve this in java, but here i am not able to do it. Any help will be appreciated.
In order to execute your local application using your own user credentials for API access temporarily you can run:
gcloud auth application-default login
You have to install sdk into your computer, that will enable you to run the code.
Then log in to your associated gmail account and you will be ready.
You can check the following documentation, to get more information.
Another option is to set GOOGLE_APPLICATION_CREDENTIALS to provide authentication credentials to your application code. It should point to a file that defines the credentials.
To get this file please follow the steps:
Navigate to the APIs & Services→Credentials panel in Cloud Console.
Select Create credentials, then select API key from the dropdown menu.
The API key created dialog box displays your newly created key.
You might want to copy your key and keep it secure. Unless you are using a testing key that you intend to delete later.
Put the *.json file you just downloaded in a directory of your choosing.
This directory must be private (you can't let anyone get access to this), but accessible to your web server code.
You can write your own code to pass the service account key to the client library or set the environment variable GOOGLE_APPLICATION_CREDENTIALS to the path of the JSON file downloaded.
I have found the following code that explains how you can authenticate to Google Cloud Platform APIs using the Google Cloud Client Libraries.
/**
* Demonstrates how to authenticate to Google Cloud Platform APIs using the
* Google Cloud Client Libraries.
*/
'use strict';
const authCloudImplicit = async () => {
// [START auth_cloud_implicit]
// Imports the Google Cloud client library.
const {Storage} = require('#google-cloud/storage');
// Instantiates a client. If you don't specify credentials when constructing
// the client, the client library will look for credentials in the
// environment.
const storage = new Storage();
// Makes an authenticated API request.
async function listBuckets() {
try {
const results = await storage.getBuckets();
const [buckets] = results;
console.log('Buckets:');
buckets.forEach((bucket) => {
console.log(bucket.name);
});
} catch (err) {
console.error('ERROR:', err);
}
}
listBuckets();
// [END auth_cloud_implicit]
};
const authCloudExplicit = async ({projectId, keyFilename}) => {
// [START auth_cloud_explicit]
// Imports the Google Cloud client library.
const {Storage} = require('#google-cloud/storage');
// Instantiates a client. Explicitly use service account credentials by
// specifying the private key file. All clients in google-cloud-node have this
// helper, see https://github.com/GoogleCloudPlatform/google-cloud-node/blob/master/docs/authentication.md
// const projectId = 'project-id'
// const keyFilename = '/path/to/keyfile.json'
const storage = new Storage({projectId, keyFilename});
// Makes an authenticated API request.
async function listBuckets() {
try {
const [buckets] = await storage.getBuckets();
console.log('Buckets:');
buckets.forEach((bucket) => {
console.log(bucket.name);
});
} catch (err) {
console.error('ERROR:', err);
}
}
listBuckets();
// [END auth_cloud_explicit]
};
const cli = require(`yargs`)
.demand(1)
.command(
`auth-cloud-implicit`,
`Loads credentials implicitly.`,
{},
authCloudImplicit
)
.command(
`auth-cloud-explicit`,
`Loads credentials explicitly.`,
{
projectId: {
alias: 'p',
default: process.env.GOOGLE_CLOUD_PROJECT,
},
keyFilename: {
alias: 'k',
default: process.env.GOOGLE_APPLICATION_CREDENTIALS,
},
},
authCloudExplicit
)
.example(`node $0 implicit`, `Loads credentials implicitly.`)
.example(`node $0 explicit`, `Loads credentials explicitly.`)
.wrap(120)
.recommendCommands()
.epilogue(
`For more information, see https://cloud.google.com/docs/authentication`
)
.help()
.strict();
if (module === require.main) {
cli.parse(process.argv.slice(2));
}
You could obtain more information about this in this link, also you can take a look at this other guide for Getting started with authentication.
Edit 1
To load your credentials from a local file you can use something like:
const Compute = require('#google-cloud/compute');
const compute = new Compute({
projectId: 'your-project-id',
keyFilename: '/path/to/keyfile.json'
});
You can check this link for more examples and information.
This other link contains another example that could be useful.
I am building a CLI app where I want to use firebase as the backend. I am using the firebase node.js sdk for this and I am running into a problem where after successful login, the firestore add / set functions stop responding and do not trigger either the "then" method or the "error" method.
const firebase = require('firebase');
// Your web app's Firebase configuration
var firebaseConfig = {
apiKey: "<REDACTED>",
authDomain: "<REDACTED>",
databaseURL: "<REDACTED>",
projectId: "<REDACTED>",
storageBucket: "<REDACTED>",
messagingSenderId: "<REDACTED>",
appId: "<REDACTED>"
};
// Initialize Firebase
var app = firebase.initializeApp(firebaseConfig);
function main() {
firebase.auth().signInWithEmailAndPassword('username', 'somepassword').then((cred) => {
console.log('Successful sign in');
firebase.firestore().collection('UserData').doc(cred.user['uid']).collection('ShellCommands').add({'Hello': 'World'}).then(function() {
console.log("Document successfully written!");
terminate();
}).catch(function(error) {
console.log(error);
});
}).catch(function(error) {
console.log(error);
});
}
main();
Now when I run this, I do see the successful sign in console log but after that the app stops and doesn't respond. It seems like its waiting for user input since the keyboard is active.
My firestore rules are open (for testing).
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write;
}
}
}
Am wondering if I messed up chaining the promise or is there something fundamentally wrong with doing it this way. Note, this will not be a server but a CLI app.
[EDITED]: The CLI app gets passed a string which it writes to firestore and exits. So everytime, the CLI is run, it would login and write the string. However, the CLI would be per user, so the user is only allowed to write to their collection. something like UserData/{UserID}/Data.