Sending http request from aws lambda to google firebse funcitons - amazon-web-services

I have set up firebase functions to receive http requests and have verified that the same is working. Now im trying to send http request to firebase from aws lambda function. But there is no response either in aws lambda or in the firebase functions log. This is my aws lambda code:
const postData = JSON.stringify({
"queryresult" : {
"parameters": {
"on": "1",
"device": "1",
"off": ""
}
}
});
const options = {
hostname: 'https://<the firebase function endpoint>',
port: 443,
path: '',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(postData)
}
};
const req = https.request(options, postData)
.then((response) => {
console.log(response);
})
.catch((err) => {
console.log(err);
});
// Write data to request body
req.write(postData);
req.end();
}
The promise part here is suppose to execute the console logs but it is not getting executed. Is there something that i'm missing here. The host is the URL that we obtain when we deploy a function. Or is there some firebase or aws related plan problem. I'am using the spark plan in firebase. Thankyou.

Related

Access to fetch blocked by CORS policy: Response to preflight request doesn't pass access control check

I am getting this error when trying to fetch REST API from Amazon Web Services in script defined html file:
Access to fetch at '$(url)' from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
script
let body = { token: params.token};
const response = await fetch(
url,
{
method: "POST",
body: JSON.stringify(body),
headers: { "Content-type": "application/json", "Access-Control-Allow-Origin":"*" },
}
);
console.log(response);
const myJson = await response.json();
console.log("response-->", myJson);
if (myJson.statusCode != 200) {
console.log("failed");
return;
}
console.log("success");
return;
}
Running into CORS error
API is deployed with below CORS configurations:
enter image description here
Once you'r done with Cors Console Enable (i see that you already done it on the image).
You need to follow this stepts to setup lambda.
And on your function include headers and response in this way:
const headers = {'Content-Type':'application/json',
'Access-Control-Allow-Origin':'*',
'Access-Control-Allow-Methods':'POST'}
const response = {
statusCode: 200,
headers:headers,
body: JSON.stringify({ token: params.token})
};
return response;
so in your fetch you could call it directly and not await it like this:
fetch(...).then((response) => {
return response.json();
})

AWS Enabling CORS for my API triggering a Lambda

I managed to create an AWS Lambda that does two things: writes on a dynamo DB and sends an SMS to a mobile number. Then I call this Lambda through a API Gateway POST call, and it works great from the Test section on AWS console but it gives error both on Postman and my own website. I inserted a callback to handle CORS on Lambda and deployed + enabled CORS on my API via console and deployed it but still get errors:
Errors via postman call: {
"message": "Internal server error"
}
Errors via my website (jquery ajax POST call): Lambda calling failed: {"readyState":4,"responseText":"{"message": "Internal server error"}","responseJSON":{"message":"Internal server error"},"status":500,"statusText":"error"}
This is my lambda code
const AWS = require('aws-sdk');
const dynamodb = new AWS.DynamoDB();
const SNS = new AWS.SNS();
const tableName = "#####";
let params = {
PhoneNumber: 'mynumber####',
Message: 'Someone wrote!'
};
exports.handler = (event, context, callback) => {
dynamodb.putItem({
"TableName": tableName,
"Item" : {
"Id": {
N: event.Id
},
"Type": {
S: event.Type
}
}
}, function(err, data) {
if (err) {
console.log('Error putting item into dynamodb failed: '+err);
}
else {
console.log('Success in writing, now starting to send SMS');
return new Promise((resolve, reject) => {
SNS.publish(params, function(err, data) {
if(err) {
console.log("Error in sending sms alarm");
reject(err);
}
else {
console.log("SMS alarm sent!");
resolve(data);
}
})
})
}
});
callback(null, {
statusCode: 200,
headers: {
"Access-Control-Allow-Headers" : "Content-Type",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "OPTIONS,POST,GET"
},
body: JSON.stringify('Hello from Lambda!'),
});
};
What am I doing wrong? I don't think permissions on lambda are the problem here, since testing it on console works both on writing on dynamo both sending the sms to my cellphone.
If I click from here on API Endpoint I get the same error {"message": "Internal server error"}
SOLUTION: instead of making an AWS HTTP API, make a AWS REST API, that is much more complex and offers more personalization for CORS, letting you set them and headers.

GCIP - enable authorization code grant flow using OIDC based external provider

Trying to configure GCIP with Salesforce Identity as IDP. Tried configuring OIDC based integration. Noticed that there is no field for providing (sfdc) client secret for OIDC based configuration. Also, the response_type=id_token is getting invoked from GCIP side. We want to use authorization code flow (response_type=code) to integrate with SFDC. Is it possible?
Code flow for OIDC providers is supported on the GCIP backend. It is just not yet exposed in the Cloud Console or the Admin SDKs.
Notice it is documented here in the REST API.
You will need to set {code: true}
Here is a snippet in Node.js (untested):
// https://cloud.google.com/identity-platform/docs/reference/rest/v2/projects.oauthIdpConfigs/patch
return new Promise((resolve, reject) => {
request({
headers: {
'Authorization': `Bearer ${accessToken}`,
'Content-Type': 'application/json',
},
url: `https://identitytoolkit.googleapis.com/admin/v2/projects` +
`/${projectId}/oauthIdpConfigs/${oidcProviderId}?updateMask=responseType`,
method: 'PATCH',
body: JSON.stringify({
responseType: {
idToken: true,
code: true,
}
}),
}, (error, response) => {
if (!error && response.statusCode === 200) {
resolve();
} else {
reject(error);
}
});
});
});

AWS API Gateway working from POSTMAN, but not from AWS Lambda function

I have an API gateway, which is working from the POSTMAN, using a valid access token, but when I call the same API gateway from inside Lambda function, I am getting 403 access denied error for the same access token. I am not sure where I am missing something. It's really weird, where everything from URL, API_KEY, access token, JSON body is the same, but worked differently in both services.
Please let me know if you have some pointers.
Here is the function that I am using for calling API Gateway -
return new Promise((resolve, reject) => {
var options = {
'method': 'POST',
'url': 'https://XXXXXXXX.execute-api.ap-south-1.amazonaws.com/dev/Patient',
'headers': {
'Content-Type': 'application/json',
'X-Api-Key': 'XXXXXXXX',
'Authorization': 'Bearer ' + accessToken
},
body: JSON.stringify({"resourceType":"Patient","active":true,"name":[{"family":"Smith","given":["Emily"]}],"gender":"female","birthDate":"1995-09-24","identifier":["1221212121"],"managingOrganization":{"reference":"Organization/2.16.840.1.113883.19.5","display":"Good Health Clinic"}})
};
request(options, function (error, response) {
if (error) throw new Error(error);
console.log(response.body);
});
});
Thanks

Permission Issue at an AWS API using Lambda

I'm testing my newly deployed AWS API using https://www.apitester.com/.
As you can see i cant access the API. The API is deployed and the Lambda code looks as following.
const AWS = require('aws-sdk');
var bucket = new AWS.S3();
exports.handler = (event, context, callback) => {
let data =JSON.parse(event.body);
var params = {
"Body": data,
"Bucket": "smartmatressbucket",
// "Key": filePath
};
bucket.upload(params, function(err, data){
if(err) {
callback(err, null);
} else {
let response = {
"statusCode": 200,
"headers": {
"my_header": "my_value"
},
"body": JSON.stringify(data),
"isBase64Encoded": false
};
callback(null, response);
}
});
};
Looking at the response log, it seems the API Gateway generates "ForbiddenException". I believe the most possible reason is using an incorrect API URL (eg- https://ogk2hm09j0.execute-api.eu-central-1.amazonaws.com/).
Suppose you configure the Lambda function to a GET method of a resource name "resourceA". Then you deploy the API to a stage named "dev". Then the correct URL should be https://ogk2hm09j0.execute-api.eu-central-1.amazonaws.com/dev/resourceA
But looking at the API URL in the logs, it seems the stage name or the resource name is not specified.