How to implement Firebase AppCheck inside firebase function to read Realtime database? [duplicate] - firebase

I recently enabled App Check for my firebase app and enforced it on both my cloud functions and database. The cloud function workflow is behaving correctly. However, I can no longer access the database from the function. A minimal version of my callable function looks something like this:
exports.myFunc = functions.https.onCall(async (data, context) => {
const adminApp = admin.initializeApp();
const ref = adminApp.database().ref('some-node');
if (context.app === undefined) {
throw new functions.https.HttpsError(
'failed-precondition',
'The function must be called from an App Check verified app.',
);
}
try {
return (await ref.orderByKey().equalTo('foo').get()).exists()
} catch(exc) {
console.error(exc);
}
});
This used to work before App Check, but now it fails and I see this in the logs:
#firebase/database: FIREBASE WARNING: Invalid appcheck token (https://my-project-default-rtdb.firebaseio.com/)
Error: Error: Client is offline.
Seems like I need to do something extra to get the admin app to pass App Check verification down to the database, but I haven't been able to find any documentation on this yet. I also tried using the app instance from functions.app.admin instead of initializing a new one, but this didn't help.
I have the latest version of the packages:
"firebase-admin": "^9.10.0"
"firebase-functions": "^3.14.1"

firebaser here
The behavior you're seeing is not how it's supposed to work, and we've been able to reproduce it. Thanks for the clear report, and sorry you encountered this.
If you (re)install the Firebase Admin SDK today, you won't be experiencing this same problem as we've fixed the problem in the #firebase/database dependency (in this PR).
If you're (still) experiencing the problem, you can check if you have the correct #firebase/database dependency by running:
npm ls #firebase/database
results look something like this:
temp-admin#1.0.0 /Users/you/repos/temp-admin
└─┬ firebase-admin#9.11.0
└── #firebase/database#0.10.8
If your #firebase/database version is lower than 0.10.8, you'll have to reinstall the Admin SDK, for example by deleting your node_modules directory and your package-lock.json file and running npm install again. This may also update other dependencies.

Related

Firebase task function failed to deploy

I havae the following firebase cloud function codes and want to deploy to my project.
exports.bgTask = functions.region(Defs.SERVER_AREA)
.tasks.taskQueue({
retryConfig: {
maxAttempts: 5,
minBackoffSeconds: 60
},
rateLimits: {
maxConcurrentDispatches: 6
},
}).onDispatch(async (data) => {
});
Obviously, the above code just copied from firebase cloud function sample and it can be run under emulator, but when I tried to deploy to server and had no luck.
I tried to run firebase functions:log command and see the following error log.
So, it seems that Firebase cli cannot recognize the taskQueue property.
I googled a lot and had no luck. The following screen shot shows the corresponding library what I am using.
Anyone has any ideas on this?
Thanks in advance!
As mentioned by #Xavier, He managed to fix the issue by creating a new project and initialize Firebase function and deployed successfully by including the packages that are needed and run the command npm install --save firebase-functions#latest for the latest version of Firebase Functions.

Firebase App Check not working with firebase functions - web project [duplicate]

I recently enabled App Check for my firebase app and enforced it on both my cloud functions and database. The cloud function workflow is behaving correctly. However, I can no longer access the database from the function. A minimal version of my callable function looks something like this:
exports.myFunc = functions.https.onCall(async (data, context) => {
const adminApp = admin.initializeApp();
const ref = adminApp.database().ref('some-node');
if (context.app === undefined) {
throw new functions.https.HttpsError(
'failed-precondition',
'The function must be called from an App Check verified app.',
);
}
try {
return (await ref.orderByKey().equalTo('foo').get()).exists()
} catch(exc) {
console.error(exc);
}
});
This used to work before App Check, but now it fails and I see this in the logs:
#firebase/database: FIREBASE WARNING: Invalid appcheck token (https://my-project-default-rtdb.firebaseio.com/)
Error: Error: Client is offline.
Seems like I need to do something extra to get the admin app to pass App Check verification down to the database, but I haven't been able to find any documentation on this yet. I also tried using the app instance from functions.app.admin instead of initializing a new one, but this didn't help.
I have the latest version of the packages:
"firebase-admin": "^9.10.0"
"firebase-functions": "^3.14.1"
firebaser here
The behavior you're seeing is not how it's supposed to work, and we've been able to reproduce it. Thanks for the clear report, and sorry you encountered this.
If you (re)install the Firebase Admin SDK today, you won't be experiencing this same problem as we've fixed the problem in the #firebase/database dependency (in this PR).
If you're (still) experiencing the problem, you can check if you have the correct #firebase/database dependency by running:
npm ls #firebase/database
results look something like this:
temp-admin#1.0.0 /Users/you/repos/temp-admin
└─┬ firebase-admin#9.11.0
└── #firebase/database#0.10.8
If your #firebase/database version is lower than 0.10.8, you'll have to reinstall the Admin SDK, for example by deleting your node_modules directory and your package-lock.json file and running npm install again. This may also update other dependencies.

FireBase sendMessage Function update to v1 Google Cloud Endpoint

So... this morning... I got an email saying:
Our records show that you own projects with App Engine applications or
Cloud Functions that are still calling the pre-GA v0.1 and v1beta1
endpoints of the App Engine and Cloud Functions metadata server.
We’re writing to let you know that these legacy endpoints are
scheduled to be turned down on April 30, 2020. After April 30, 2020,
requests to the v0.1 and v1beta1 endpoints will no longer be
supported, and may return HTTP 404 NOT FOUND responses.
I'm only using Firebase Functions to send messages... and the email went on to identify my sendMessage function as the culprit. But I can't... for the life of me... figure out WHERE I need to update the endpoints. My sendMessage function is as follows:
exports.sendMessage = functions.database.ref('/messages/{receiverUid}/{senderUid}/{msgId}')
.onWrite(async (change, context) => {
const message = change.after.val().body;
const receiverUid = change.after.val().receiverUid;
const senderUid = change.after.val().senderUid;
const msgId = change.after.val().msgId;
if (!change.after.val()) {
return console.log('Sender ', senderUid, 'receiver ', receiverUid, 'message ', message);
}
console.log('We have a new message: ', message, 'for: ', receiverUid);
I've tried following some of the Curl suggestions from this link: https://cloud.google.com/compute/docs/migrating-to-v1-metadata-server
...but every time I try one of them I get:
curl: (6) Couldn't resolve host 'metadata.google.internal'
So... at this point... I have no idea what it is I'm supposed to change or where I'm supposed to look. Any help would be appreciated.
I had this same problem, and didn't see any of the libraries I was using listed here.
In my case, the culprit turned out to be firebase-admin. I was using version 7.3.0, and I found this gem:
$ grep -rni "computeMetadata/" *
firebase-admin/lib/auth/credential.js:30:var GOOGLE_METADATA_SERVICE_PATH = '/computeMetadata/v1beta1/instance/service-accounts/default/token';
So, I updated my Cloud Functions libraries as shown here:
npm install firebase-functions#latest --save
npm install firebase-admin#latest --save-exact
and then, voila!
$ grep -rni "computeMetadata/" *
node_modules/firebase-admin/lib/auth/credential.js:30:var GOOGLE_METADATA_SERVICE_PATH = '/computeMetadata/v1/instance/service-accounts/default/token';
Then I redeployed and problem solved.
I searched at the https://github.com/firebase/firebase-functions repo latest version (3.3.0), and I found the file: spec/fixtures/https.ts. Inside this file there are some mock functions, which use the old: /computeMetadata/v1beta1 endpoint.
This might mean that firebase-functions modules package should be updated to use the /computeMetadata/v1 endpoint instead.
Fwiw I found this old dependency in package.json was dragging in other very old packages:
"#google-cloud/functions-emulator": "^1.0.0-beta.6",
In particular it brought in gcs-resumable-upload v 0.10.2, which is below the v 0.13.0 recommended by google (see https://cloud.google.com/compute/docs/migrating-to-v1-metadata-server#apps-to-update). Probably others too.
The fix was to either:
remove #google-cloud/functions-emulator, or
switch to its modern replacement, #google-cloud/functions-framework

Deploying Function Error on Cloud Function with error code 13 and Message "INTERNAL"

I'm deploying a Firestore trigger onCreate for my App, but everytime I want to deploy, it always Error
the console always showing Code 13 and Message "INTERNAL"
this is what comes up on Console
{"#type":"type.googleapis.com/google.cloud.audit.AuditLog",
"status":{"code":13,"message":"INTERNAL"},
"authenticationInfo":{"principalEmail":"[My_EMAIL]"},
"requestMetadata":{"requestAttributes":{},"destinationAttributes":{}},
"serviceName":"cloudfunctions.googleapis.com",
"methodName":"google.cloud.functions.v1.CloudFunctionsService.UpdateFunction",
"resourceName":"projects/etalase/locations/us-central1/functions/onNewMessage"}
this is my code on index.js
exports.onNewMessage = functions.firestore
.document('/messages/{groupChatId}/{groupChatId}/{messageFeedItem}')
.onCreate(async (snapshot, context) => {
const doc = snapshot.data();
console.log('------Message Created-----');
console.log(doc);
const idForm = doc.userID;
const idTo = doc.sellerID;
console.log('Message from : ', idForm);
console.log('Message to : ', idTo);
});
I expect this will deploy and every time a new message created on {messageFeedItem}, it will trigger the console, but even I can't deploy it
Thank you
So right now I can deploy the function by changing the directory
'messages/{groupChatId}/{groupChatId}/{messageFeedItem}'
into
'messages/{groupChatId}/{groupChatId2}/{messageFeedItem}'
my speculation is you can't have same name to the wildcard
You have to import firebase functions
import functions = require('firebase-functions');
or
const functions = require('firebase-functions');
If you did, then check your package.json
For anyone who got this far and still does not have a solution - here is what was wrong in my case
exports.fnName = functions.firestore
.document('Collection/{collId}/SubCollection/{subCollId')
.onUpdate((change, context) => {
...
});
Note the missing '} at the end of the document reference.
This caused the deploy to fail with the following on the client
Failed to configure trigger provider
And with the following in the function logs
"status":{
"code":13,
"message":"INTERNAL"
},
Set up Node.js and the Firebase CLI
In many cases, new features and bug fixes are available only with the
latest version of the Firebase CLI and the firebase-functions SDK.
It's a good practice to frequently update both the Firebase CLI and
the SDK with these commands inside the functions folder of your
Firebase project:
npm install firebase-functions#latest firebase-admin#latest --save
npm install -g firebase-tools
my issue is because I use - character in my wild card
'chat/{abc-efg}'
I change - to _ and it works

Error with Firebase on Electron app: Failed to load gRPC

I'm building an Electron app, and in the renderer.js file, I'm using Firebase Admin to get Firestore data. However, whenever I run it, it returns this error in the logs..
Error: Failed to load gRPC binary module because it was not installed for the current system
Expected directory: electron-v2.0-darwin-x64-unknown
Found: [node-v48-darwin-x64-unknown]
This problem can often be fixed by running "npm rebuild" on the current system
I tried to run "npm rebuild", but it still didn't fix it.
I also tried updating Firebase Admin and gRPC.
Here is the code from the renderer.js file...
// This file is required by the index.html file and will
// be executed in the renderer process for that window.
// All of the Node.js APIs are available in this process.
const admin = require('firebase-admin');
var serviceAccount = require('./credentials.json');
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://mytestapp.firebaseio.com"
});
var db = admin.firestore();
const settings = {
timestampsInSnapshots: true
};
db.settings(settings);
function LoadList() {
db.collection("Orders").get().then(function(Collection){
Collection.forEach(function(OrderDoc){
console.log(OrderDoc.id)
})
}).catch(function(err){
console.error(err);
});
}
document.querySelector('#ListSec').addEventListener('click', LoadOrderList)
Any ideas? I've been trying to solve this for hours, but can't seem to figure it out.
That error message indicates that gRPC was installed for Node, not for Electron. Electron has a different binary interface, so binary modules like gRPC need to be installed specifically for Electron. You can generally do this just by running npm rebuild --runtime=electron --target=2.0.0 (modified to match the version of Electron you want to use).
The original answer by #murgatroid99 was helpful at the time, and a postinstall command worked great up until electron v7, where the issue returned.
For anyone else who comes across this issue, I've found a better solution:
the electron-rebuild package
npm install electron-rebuild --save-dev
Run it using
npx electron-rebuild
Or, add it as a postinstall command
{
...
"scripts": {
"postinstall": "electron-rebuild"
},
...
}
Further information is in the official Electron Documentation

Resources