firebase 9 permission denide from localhost - node.js

i'm using Firebase version 9 (MODULAR) as database for a web application in nodejs v18.
When i try to access data from localhost i get the error below, but from an heroku deployment works like a charm.
[2022-06-26T07:32:22.447Z] #firebase/firestore: Firestore (9.8.4): Connection GRPC stream error. Code: 7 Message: 7 PERMISSION_DENIED: Permission denied on resource project "my_project",.
[2022-06-26T07:32:22.447Z] #firebase/firestore: Firestore (9.8.4): Could not reach Cloud Firestore backend. Connection failed 1 times. Most recent error: FirebaseError: [code=permission-denied]: 7 PERMISSION_DENIED: Permission denied on resource project "my_project",.
This typically indicates that your device does not have a healthy Internet connection at the moment. The client will operate in offline mode until it is able to successfully connect to the backend.
[2022-06-26T07:32:22.466Z] #firebase/firestore: Firestore (9.8.4): Connection GRPC stream error. Code: 7 Message: 7 PERMISSION_DENIED: Permission denied on resource project "my_project",.
node:internal/process/promises:288
triggerUncaughtException(err, true /* fromPromise */);
^
[FirebaseError: Failed to get document because the client is offline.] {
code: 'unavailable',
customData: undefined,
toString: [Function (anonymous)]
}
Node.js v18.0.0
For context:
the web app its an internal tool so i do my own authentication server-side and then the app makes some checks on some data on the firestore db. So basically who makes the queries its the app,not the user. This makes me thing that i should use a service account with firestore-admin api.
The problem is that the provided code snippet from the docs,does not work for me..
var admin = require("firebase-admin");
var serviceAccount = require("path/to/serviceAccountKey.json");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount)
});
And i already changed the access rule to be the horribly unsecure one:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if true;
}
}
}
Any idea on what i should do? Or maybe why it doesnt work on local development?
Since the documentation it an incomplete maze of stuff i am probably missing something..
Thanks to anyone that can help! (at least to understand why)

As the GitHub link suggests, the issue might be due to useFetchStreams being enabled by default, in the new modular build (v9).
Hence, modify your code accordingly:
import {initializeFirestore} from 'firebase/firestore'
const db = initializeFirestore(firebaseApp, {useFetchStreams: false})
Also, the error might arouse not because the android device or emulator you are debugging is offline but because the "databaseURL" setting was missing in the part that defines the Firebase configuration object. I think that the same error might occur if the setting is incorrect.
Also, I suggest you have a look at this Stackoverflow case, which talks in detail about all the probable reasons behind the ‘Client is offline’ issue.
However, if the above solution does not, suggest you enable debug logging by calling setLogLevel.
firebase.firestore.setLogLevel('debug');

Related

Timeout when communicating with Web3 Provider

Background
I am trying to investigate and solve problems with a containerized NodeJS web service app that communicates with Avalanche Test Network (https://api.avax-test.network/ext/bc/C/rpc) in order to Mint NFTs.
//...
provider = new HDWalletProvider({
privateKeys: [walletPrivateKey],
providerOrUrl: "https://api.avax-test.network/ext/bc/C/rpc",
pollingInterval: 4000,
});
const myContract = Contract(Contract_NFT);
myContract.setProvider(provider);
const _instance = await myContract.at(process.env.CONTRACT_NFT_ADDRESS);
_instance.mint(provider.getAddress(), mintURL, { from: provider.getAddress() })
//...
Note: I am not the developer of app.
Issue
After starting the container, first request completes successfully. However subsequent requests fail with code: -32603 message: 'ETIMEDOUT' error
at new NodeError (node:internal/errors:387:5)
at Web3ProviderEngine.emit (node:events:502:17)
at /app/node_modules/web3-provider-engine/index.js:54:14
at afterRequest (/app/node_modules/web3-provider-engine/index.js:148:21)
at /app/node_modules/web3-provider-engine/index.js:174:21
at /app/node_modules/web3-provider-engine/index.js:232:9
at /app/node_modules/async/internal/once.js:12:16
at replenish (/app/node_modules/async/internal/eachOfLimit.js:61:25)
at /app/node_modules/async/internal/eachOfLimit.js:71:9
at eachLimit (/app/node_modules/async/eachLimit.js:43:36)
at /app/node_modules/async/internal/doLimit.js:9:16
at end (/app/node_modules/web3-provider-engine/index.js:211:5)
at Request._callback (/app/node_modules/web3-provider-engine/subproviders/rpc.js:36:21)
at self.callback (/app/node_modules/request/request.js:185:22)
at Request.emit (node:events:513:28)
at Timeout.<anonymous> (/app/node_modules/request/request.js:851:16)
Error: PollingBlockTracker - encountered an error while attempting to update latest block:
undefined
at PollingBlockTracker._performSync (/app/node_modules/eth-block-tracker/src/polling.js:51:24)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
When the app is used outside a container and directly on server OS, all requests successfully complete.
What I have tried
I tried searching the internet forums and boards. Similar issue is mentioned in some posts but suggested solution is to tweak Timeout/Interval values which did not help with my issue and still got the error.
I tried using the same NodeJS and NPM versions installed on server OS. Also tried using different versions of NodeJS( 14.XX, 16.XX). Still got the same error.
Also I have tried changing and configuring Docker network( different type of network driver, different IPAM config, passing extra hosts etc.). Still got the same error.
I have confirmed that mentioned URL is accessible from inside container using ping, nc and dig tools. Also have confirmed that successful HTTPS connection is being established.
Questions
What is causing this behavior?
What I can do to reliably use this app inside container?
Have I missed something?

UnhandledPromiseRejectionWarning: error: permission denied for table

I'm building a node express web application that interfaces with a postgres database using node-pg. In my local environment everything runs fine but when I pull the project from github on a different machine and try to run it I get the following error:
(node:445) UnhandledPromiseRejectionWarning: error: permission denied for table <some table>
I'm not sure why I'm getting this error as I am connecting to the same database with the same credentials as from the local environment, and I've tried to make sure the proper privileges are granted by using the command GRANT ALL PRIVILEGES ON TABLE <some table> TO postgres; and then restarting the database service.
Is there something I'm missing or how would I go about solving this issue?
While I can't suggest an overall fix for your connection issues we can fix the UnhandledPromiseRejectionWarning by literally handling the Promise rejection.
try {
// connect to pg
}
catch(e) {
console.error(e)
// Probably if you can't connect to the DB at all that's an unrecoverable problem.
// I'd log whatever useful stats about the running application as you can and then maybe just end the process.
process.exit(1)
}
Note the docs for process.exit() though, that "This means that any callback that's pending, any network request still being sent, any filesystem access, or processes writing to stdout or stderr - all is going to be ungracefully terminated right away." which may or may not be a problem for you.

Repeated 'Too many certificates already issued for exact set of domains' error with GreenLock package

I have already checked this post. But even though I tried that method, it didn't work, so I open a new issue.
I use AWS EC2 server and deploy with aws pipeline. So When I push to github repository, it will automatically build and deploy to production server.
At first it's works fine, and there are no errors in the console.
But one day an error began to occur. So when I checked the console, there was an error as below.
[Error Message in console]
set greenlockOptions.notify to override the default logger
certificate_order (more info available: account subject altnames challengeTypes)
Error cert_issue:
[acme-v2.js] authorizations were not fetched for 'mydomain.com':
{"type":"urn:ietf:params:acme:error:rateLimited","detail":"Error creating new order :: too many certificates already issued for exact set of domains: mydomain.com: see https://letsencrypt.org/docs/rate-limits/","status":429,"_identifiers":[{"type":"dns","value":"mydomain.com"}]}
Error: [acme-v2.js] authorizations were not fetched for 'mydomain.com':
{"type":"urn:ietf:params:acme:error:rateLimited","detail":"Error creating new order :: too many certificates already issued for exact set of domains: mydomain.com: see https://letsencrypt.org/docs/rate-limits/","status":429,"_identifiers":[{"type":"dns","value":"mydomain.com"}]}
at Object.E.NO_AUTHORIZATIONS (/home/project/build/node_modules/#root/acme/errors.js:75:9)
at /home/project/build/node_modules/#root/acme/acme.js:1198:11
at processTicksAndRejections (internal/process/task_queues.js:97:5)
Error cert_issue:
[acme-v2.js] authorizations were not fetched for 'mydomain.com':
In my opinion, I think there was a limit to the process of reissuing the certificate every time I push the code, but I don't know where the problem occurred even if I check the code.
My code structure is written as below and developed with Express.
[server.js]
"use strict";
const app = require("./app.js");
require("greenlock-express")
.init({
packageRoot: __dirname,
configDir: "./greenlock.d",
// contact for security and critical bug notices
maintainerEmail: process.env.EMAIL,
// whether or not to run at cloudscale
cluster: false
})
// Serves on 80 and 443
// Get's SSL certificates magically!
.serve(app);
[greenlock.d/config.json]
{ "sites": [{ "subject": "mydomain.com", "altnames": ["mydomain.com"] }] }
[.greenlockrc]
{"configDir":"./greenlock.d"}
[package.json (scripts.start line)]
"scripts": {
"start": "node server.js"
},
I am aware of the seven-day limit from Let's Encrypt. So I want to find a way to solve this problem.
in my express folder, I do
sudo chmod 775 ./greenlock.d
then I delete greenlock.d(one time) and npm start
I dont have issue since

Azure service bus: with RootManageSharedAccessKey, still complains 'Listen' claim(s) required?

I have an error-handler passed to a service bus client "receive" function and it is firing after setup as follows:
const ns = Namespace.createFromConnectionString(connectionString);
const client = ns.createQueueClient(queueName);
const receiver = client.getReceiver();
receiver.receive(onMessageHandler, onErrorHandler, { autoComplete: false });
with the error:
UnauthorizedError: Unauthorized access. 'Listen' claim(s) are required to perform this operation.
The connection string being used uses the default root shared access key which has all claims (listen, send AND manage). Why am I getting this error / how to fix it? Thx.
I don't know if this helps anyone but in my case, I had the old azure-sb package still kicking around, and it may have been polluting my node_modules in some in explicable way. Getting rid of it seems to have gotten rid of the claims complaints.

Azure Redis Cache: "role discovery data is unavailable"

I'm trying to connect to an instance of Azure Redis Cache from my local dev machine. I'm using StackExchange.Redis like so:
var lazyConnection = new Lazy<ConnectionMultiplexer>(() =>
{
return ConnectionMultiplexer.Connect(
$"{redisServerUrl},abortConnect=false,ssl=true,password={redisServerKey},connectTimeout=10000,syncTimeout=10000");
});
When lazyConnection is called I get an InvalidOperationException with the message:
"role discovery data is unavailable"
and this one-liner stack trace:
Microsoft.WindowsAzure.ServiceRuntime.RoleEnvironment.get_CurrentRoleInstance()
Why is the exception thrown and how can I avoid it?
StackExchange.Redis tries to discover the RoleInstance name under the covers if you don't specify a ConfigurationOptions.ClientName value. It is odd that you are getting this error bubbled out to your code because the code in question handles all exceptions and defaults back to returning the Computer name.
I suspect that if you add ",name=XXX" to your connection string, the error will go away because you will avoid that code path.

Resources