getting error : Your client does not have permission to get URL in firebase functions - node.js

i am new in firebase, i have deploy one function, and it is using get method,
https://us-central******.cloudfunctions.net/addMessage
when i try to run this api, i am getting below error
Error: Forbidden
Your client does not have permission to get URL /addMessage from this server.
Can anyone please help me to resolve this issue ?
exports.addMessage = functions.https.onRequest(async (req, res) => {
// Grab the text parameter.
const original = req.query.text;
// Push the new message into the Realtime Database using the Firebase Admin SDK.
const snapshot = await admin.database().ref('/messages').push({ original: original });
// Redirect with 303 SEE OTHER to the URL of the pushed object in the Firebase console.
res.redirect(303, snapshot.ref.toString());
});

From the doc, argument --allow-unauthenticated:
Specifies that the function does not require authentication to invoke. By default HTTP functions require authentication. If you do not include this flag the first time you deploy an HTTP function, you are prompted to allow unauthenticated invocations. You are not prompted on subsequent invocations.
So, you need to deploy the cloud functions with this argument if you don't need authentication. E.g.
A simple cloud function, index.js:
exports.helloHttp = (req, res) => {
res.send(`Hello ${req.body.name || 'World'}!`);
};
Deploy without --allow-unauthenticated:
gcloud beta functions deploy helloHttp --trigger-http --runtime nodejs10
When you access the endpoint of this cloud function: https://us-central1-xxxx-218801.cloudfunctions.net/helloHttp. You will get this 403 Forbidden error:
Error: Forbidden
Your client does not have permission to get URL /helloHttp from this server.
Deploy with --allow-unauthenticated:
gcloud beta functions deploy helloHttp --trigger-http --runtime nodejs10 --allow-unauthenticated
You will get access the endpoint without authentication.
Hello World!

I ran into this (or a very similar problem) today. When I invoked one of my functions from Postman, I got:
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<title>401 Unauthorized</title>
</head>
<body text=#000000 bgcolor=#ffffff>
<h1>Error: Unauthorized</h1>
<h2>Your client does not have permission to the requested URL
<code>/myApi/somePath?</code>.</h2>
<h2></h2>
</body>
</html>
I try redeploying the functions but that didn't work.
Solution: Delete your functions and deploy them again.
What I did was:
Exported a single dummy function from functions/index.ts and removed my original functions.
Deployed. That deleted my original functions.
Verified that the dummy function worked well.
Restored my original functions and deployed again.
Verified that my original functions worked.
Background and possible cause
I had a new Firebase project and I tried to deploy my functions many times but got some errors related to permissions. I guess that left the functions in a weird state...
I managed to deploy the functions successfully later, but they were not in a good state and I got that error response from Postman when I called one of them.
The errors I got were the following:
Error 1:
Error: Missing permissions required for functions deploy. You must have permission iam.serviceAccounts.ActAs on service account some-sa#appspot.gserviceaccount.com.
Error 2:
Error: Missing permissions required for functions deploy. You must have permission iam.serviceAccounts.ActAs on service account some-sa#appspot.gserviceaccount.com.
Error 3:
Unable to set the invoker for the IAM policy on the following functions:
someFunction1(us-central1)
someFunction2(us-central1)
Some common causes of this:
- You may not have the roles/functions.admin IAM role. Note that roles/functions.developer does not allow you to change IAM policies.

After trying to delete individualy functions and uploading them again ultimately i had to delete all of the previously deployed functions and deploy them all.
Once i'd done that a couple of times, the functions deployed.
There are two possible causes i can think of that was causing this, both very ambiguous.
I found that there was one offending file, and the only thing that fixed the deploy was to change the length of the file name. Yes, the length of the filename. One character too long and the deployment failed. If this was a windows 95 machine i'd have said the inheritance chain path was too long for the compiler. However, compiliation and running on the emulator worked fine. So who knows.
I had tried to set up cloud build, and left that part half finished. I had updated the .firebaserc as a part of that. Perhaps, just perhaps, the deployment didn't like the fact the default projects list had changed, and didn't match the existing functions.
I'm totally guessing as to the cause, but because the error is so ambiguous, with no apparent cause, figued this might help people find the cause.

It can also happen, if you use the wrong subpath. For me the url was somehow wrong, instead of resendConfirmEmail it tried to call resendConfirmEmail%20. That function didn't exist and google responded with 403:
https://europe-west1-my-project.cloudfunctions.net/resendConfirmEmail%20?userId=imFeBoV...&email=gr...%40...com
when it should have been:
https://europe-west1-my-project.cloudfunctions.net/resendConfirmEmail?userId=imFeBoV...&email=gr...%40...com

Related

SAP Cloud SDK for javascript using the destination

I have followed the Tutorial and build the basic CF based nodejs applciation to display all BusinessPartners from my S/4HANA on-premise destination.
function getAllBusinessPartners(): Promise<BusinessPartner[]> {
return BusinessPartner.requestBuilder()
.getAll()
.execute({
destinationName: 'MockServer'
});
}
Destination is configured with the Virtual host from cloud connector.
But after deploying to the Cloud Foundry, i get following error for the GET request
{"message":"Service of type destination is not supported! Consider providing your own transformation function when calling destinationForServiceBinding, like this:\n destinationServiceForBinding(yourServiceName, { serviceBindingToDestination: yourTransformationFunction });","level":"warn","custom_fields":{"package":"core","messageContext":"destination-accessor"},"logger":"sap-cloud-sdk-logger","timestamp":"2020-03-09T18:15:41.856Z","msg":"Service of type destination is not supported! Consider providing your own transformation function when calling destinationForServiceBinding, like this:\n destinationServiceForBinding(yourServiceName, { serviceBindingToDestination: yourTransformationFunction });","written_ts":1583777741856,"written_at":"2020-03-09T18:15:41.856Z"}
The application is already bound to the Destination service as well.
Can someone help me here, what went wrong ? or the approach to use destination is different in the new version of Cloud-SDK ?
After lot of attempts, i have made this to work.
My Observations:
Connectivity service is also required to be bound, when using on-premise S4 backend.
There was no errors in the log, i have made certain modification in the code to use async/await
async function getAllBusinessPartners(): Promise<BusinessPartner[]> {
return await BusinessPartner.requestBuilder()
.getAll()
.execute({
destinationName: 'MockServer'
});
}
After this modification, when I hit the GET request, it gave me the following error:
"Failed to get business partners - get request to http://s4h-scc-basic:500/sap/opu/odata/sap/API_BUSINESS_PARTNER/sap/opu/odata/sap/API_BUSINESS_PARTNER failed!"
Could notice that the suffix after the http://domain:port is twice. One I gave in the destination, and the other VDM adds automatically.
Ideally, this error is supposed to be thrown even before adding async/await.
After removing the suffix from the destination, it started to work.
If your request really does error, what you posted here from your logs is most likely not the reason for the failure. We are aware that this message is confusing and will improve it (https://github.com/SAP/cloud-sdk/pull/32).
Can you check whether there are more errors in your logs? Based on the code you posted and the setup you described, this should work. Do you have a binding to the XSUAA service.

How do I get my deployed React.js app to use API secret keys? I'm using Heroku confing vars but still not working

Problem:
I created a simple React app (using Javascript and Node) that uses the GitHub API to search for users and return information about them. I need to use a GitHub oauth key so that I can make authenticated API requests. However, I am having trouble giving my deployed app (using Heroku) the key without hard-coding it into the API call. I'm fairly new at this so any help would be great! I linked the github repo at the bottom of this post.
I have tried several things which I will explain below:
Attempt 1:
I created a file where I set my GitHub key to a variable and exported it (Image of code)
I put said file in the .gitignore
I imported the variable in the files where I made API calls and used them it directly in the API call. (Image of API call)
This worked on my dev environment but (obviously) did not work on my deployed Heroku app because it had no idea what the variable was. (Image of error)
Attempt 2:
I configured variables in Heroku and set GITHUB_KEY to my key. (Image of Heroku variable setting).
Next, I checked that Heroku recognized this variable by running the command heroku config:get GITHUB_KEY and received the correct key in response (Image of terminal)
In my secrets file, I set the variable like so: process.env.GITHUB_KEY = 'a93b2c21918b42df5a28e0e529c627ee22c60de4'; (Image of setting variable using process.env)
And then I use it in my API calls on the frontend: const res = await fetch(
'https://api.github.com/users/${this.state.input}?access_token=${process.env.GITHUB_KEY}'
);.
However, I get the following error: SearchBar.js:32 GET https://api.github.com/users/livmarx?access_token=undefined 401 (Unauthorized). (Image of error).
So, I know that I'm misunderstanding how process.env works but cannot seem to figure it out! Any clarification would be super helpful.
Here is the link to my github repo: https://github.com/livmarx/zilliow-challenge

Firebase functions - Failed to retrieve function source code

I get the error: "Failed to retrieve function source code" when I try and deploy a function.
This is all from the command line. I am using node 6.11.5 (but in the firebase-admin package.json file in the nodes folder it is says node 6.9.1 is used to download that). I am using firebase-admin#5.8.1 and firebase-functions#0.8.1.
This is the code in my index.js file that I am trying to deploy:
const functions = require('firebase-functions');
exports.helloWorld = functions.https.onRequest((request, response) => {
response.send("Hello from Firebase!");
});
I have also tried to deploy many different things.
Two interesting things:
- I used to be able to deploy any function without problem. This changed about a month ago and now every function I try gets this error. I can't remember making any change that would be related to this.
- Also I can deploy functions from my computer (with the exact same set up and firebase versions) to other projects in the same google account and different google accounts without any problem.
Thanks
I think you should check your billing settings in google cloud. I got the same problem and after updating billing information then redeploy the function, the error is gone.

Cloud Functions for Firebase error: "400, Change of function trigger type or event provider is not allowed"

When I run firebase deploy I get this error message:
functions: HTTP Error: 400, Change of function trigger type or event provider is not allowed
TL;DR
firebase functions:delete yourFunction // this can be done via the Firebase Console as well
firebase deploy
Explanation
Basically, Cloud Functions expects the same trigger for every function all the time, i.e. once it is created it has to stick to its original trigger because every function name is connected to a specific trigger. The trigger can therefore only be changed by deleting the function first and then creating it again with a different trigger.
This can now be done easily by using the functions:delete command:
firebase functions:delete yourFunction
The documentation features more advanced use cases as well.
Old solution
Solution of this is basically commenting or cutting out your function and then saving the Functions file and deploying. The function will get deleted in Firebase, but after that you can insert/uncomment your function and it will deploy just fine again. This error occurs when you take a function and change the type of trigger that it uses, i.e. HTTP, database or authentication.
Firstly cut it out
/* exports.yourFunction = someTrigger... */
And then, after deploying ("firebase deploy") replace your trigger
exports.yourFunction = anotherTrigger...
For those who stumble upon this in the future, the Cloud Functions console now offers a delete button.
You can also go to the Cloud Functions panel in the Google Cloud Platform console and delete your function from there. After that you can upload the function normally from firebase CLI. Not sure why they don't have a delete function option in the firebase console.

What is the proper way to use the bluemix.getServiceCreds() function in node.js?

I have cloned the Concept Insights demo from Bluemix and made some minor changes to use my own corpus. It runs OK locally, but when I deploy it to Bluemix I get an authorization error when it tries to access my corpus. I'm certain that the error is a result of the early call in app.js to bluemix.getServiceCreds('concept_insights'), which apparently replaces my service credentials with some that must be stored in the environment on Bluemix.
Can someone explain the purpose of this function, and the proper approach to what I am trying to do? I could probably just delete the call to that function, but I'm afraid that I may be missing part of the larger picture if I do. Is this a way to keep my credentials out of the code base? If so, how do I make it work?
bluemix.getServiceCreds('concept_insights') gets the concept_insights service credentials from the VCAP_SERVICES variable that is created by Bluemix. (see VCAP_SERVICES)
You probably want to use the credentials from the environment instead of hardcoding them in your app.js file.
When your app runs locally you hardcode the credentials in app.js, but when it runs in Bluemix those credentials are overwritten. If you don't want this to happen remove the bluemix.getServiceCreds('concept_insights')
var credentials = {
url: 'https://gateway.watsonplatform.net/concept-insights/api',
username: '<username>',
password: '<password>',
version: 'v2'
};
When creating a service make sure you use the Standard plan.
If you use the Beta plan you will have to use https://gateway.watsonplatform.net/concept-insights/api as url.

Resources