How to pass httpOptions in aws-sdk DocumentClient constructor? - javascript

I am having serious performance issues with aws-sdk when I deploy my application to AWS.
I'm using it like below:
wrapper = {
accessKeyId: "YOURACCESSKEY",
secretAccessKey: "YOURSECRETKEY",
region: "us-east-1",
endpoint: new AWS.Endpoint('http://localhost:8000')
};
AWS.config.update(wrapper);
const docClient = new AWS.DynamoDB.DocumentClient();
module.exports ={"docClient":docClient};
I researched and found that - https://github.com/aws/aws-sdk-js/issues/900 - we can specify httpOptions in the aws so that keepAlive is enabled.
My questions is, how do I specify the httpOptions in the AWS-sdk constructor above:
var dynamo = new AWS.DynamoDB({
region: "ap-southeast-2",
httpOptions: {
agent: new https.Agent({
rejectUnauthorized: true,
keepAlive: true
})
}
});
how to add this to the wrapper config. It doesn't accept any extra httpOptions key in AWS.config.update

It should be something like this..
new AWS.DynamoDB.DocumentClient({
service: new AWS.DynamoDB({
region: "ap-southeast-2",
httpOptions: {
agent: new Https.Agent({ keepAlive: true })
}
})
})
It has to be added to DocumentClient, not the DynamoDB itself.

Related

How to hard code credentials AWS SES JS SDK V3

AWS forced me to upgrade do SDK V3, and now I'm having such a hard time setting up my credentials. They used to be hard-coded like:
AWS.config.update({
apiVersion: "2010-12-01",
accessKeyId: "MYKEY",
secretAccessKey: "MYOTHERKEY",
region: "us-east-1",
});
But now the AWS package is deprecated in favor of the modularized #aws-sdk/client-ses.
How to hard code my credentials as I used to do in this new version of the SDK?
What I have so far:
import {
SESClient,
CloneReceiptRuleSetCommand,
} from "#aws-sdk/client-ses";
const client = new SESClient({
accessKeyId: "MYKEY",
secretAccessKey: "MYOTHERKEY",
region: "us-east-1",
});
const command = new CloneReceiptRuleSetCommand(params);
client.send(command)
But it returns me the error "CredentialsProviderError: Could not load credentials from any providers"
P.S.: I know the disadvantages of hard-coding credentials, but this is not a issue for this application in particular. It's a backend Node.js service, and only I need to have access to it.
The key and the secret need to be in the credentials object of the configuration object.
Also, for CloneReceiptRuleSetCommand, you need to provide OriginalRuleSetName and RuleSetName.
So, it should be like this:
import {
SESClient,
CloneReceiptRuleSetCommand,
} from "#aws-sdk/client-ses";
const client = new SESClient({
credentials: {
accessKeyId: "MYKEY",
secretAccessKey: "MYOTHERKEY"
},
region: "us-east-1",
});
const params = {
OriginalRuleSetName: 'RULESET_TO_CLONE',
RuleSetName: 'TARGET_RULESET'
}
const command = new CloneReceiptRuleSetCommand(params);
client.send(command)
References:
Type definition for the SESClient constructor config
Type definition of the credentials object
Constructor definition of the CloneReceiptRuleSetCommand

Error while calling AWS Athena using javascript code using Cognito UnauthRole with Full S3 and Athena Access

I am trying to query athena by assuming a role by using Cognito_IdedtityPool to get temporary accessKey, secretKey and sessionToken which has full Athena and S3 permission. But when i call it from my .js file it throws error
User:
Error : arn:aws:sts::<acc_no>:assumed-role/... is not authorized to perform: athena:StartQueryExecution on resource: arn:aws:athena:us-east-1:... because no session policy allows the athena:StartQueryExecution action
But once I create an IAM User and hardcode the keys with full Athena and S3 permission. then i am able to get data. Can anyone help in this ?
How can i query using assumed role ?
My js code is below :
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
IdentityPoolId: 'us-east-1:<pool-id>',
});
var config = {
accessKey: credentials.accessKeyId, // REQUIRED
secretKey: credentials.secretAccessKey, //REQUIRED
sessionToken: credentials.sessionToken,// REQUIRED
region: 'us-east-1',
apiVersion: '2017-05-18',
}
AWS.config.update(config);
const AthenaExpress = require("athena-express"),
const athenaExpressConfig = {
aws: AWS,
s3: "s3://athena-output-destination/Test",
getStats: true,
workgroup: 'primary',
catalog: ATHENA_CATALOG,
retry: 4,
formatJson: true,
};
const athenaExpress = new AthenaExpress(athenaExpressConfig);
(async () => {
let myQuery = {
sql: query_string,
db: ATHENA_DB
};
try {
let results = await athenaExpress.query(myQuery);
console.log(results);
} catch (error) {
console.log(error);
}
})();

SignatureDoesNotMatch error when sending an email from Node AWS SDK (Simple Email Service)

I try to send an email with the #aws-sdk/client-ses SDK in Node but I get:
SignatureDoesNotMatch: The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.
Here is my code:
const aws = require("#aws-sdk/client-ses");
async function main() {
const ses = new aws.SES({
region: "eu-west-3",
credentials: {
accessKeyId: "REDACTED",
secretAccessKey: "REDACTED"
}
});
await ses.sendEmail({
Destination: {
ToAddresses: ["REDACTED#REDACTED.com"]
},
Message: {
Subject: {
Charset: "UTF-8",
Data: "Test email"
},
Body: {
Text: {
Charset: "UTF-8",
Data: "This is the message body in text format."
}
}
},
Source: "REDACTED#REDACTED.com"
});
}
main().catch(console.error);
Is there something wrong with this code?
Thank you
OK I found my mistake: I was using the access key generated with the user, that is in fact a SMTP login/password, not an access key that you can use in the SDK (even if it appears under access keys in IAM).
The solution is to create a new access key in IAM, then I used nodemailer (because otherwise my code used the action ses:SendEmail instead of ses:SendRawEmail)
const nodemailer = require("nodemailer");
const aws = require("#aws-sdk/client-ses");
async function main() {
let transporter = nodemailer.createTransport({
SES: {
ses: new aws.SES({
region: "eu-west-3",
credentials: {
accessKeyId: "REDACTED",
secretAccessKey: "REDACTED"
}
}),
aws
}
});
await transporter.sendMail({
from: "REDACTED#REDACTED.com",
to: "REDACTED#REDACTED.com",
subject: "Test email",
text: "This is the message body in text format."
});
}
main().catch(console.error);

How to access request headers in custom graphQL resolvers when using neo4j-graphql-js?

When trying:
const server = new ApolloServer({
schema: schema,
context: { req, driver, neo4jDatabase: process.env.NEO4J_DATABASE },
introspection: true,
playground: true,
})
error: req is not defined
and when trying:
const server = new ApolloServer({
schema: schema,
context: ({ res }, driver, neo4jDatabase = process.env.NEO4J_DATABASE) => (
res, driver, neo4jDatabase
),
introspection: true,
playground: true,
})
error: No Neo4j JavaScript driver instance provided.
I've already tried a lot of different ways of writing it and reading Apollo source code but no success.
Solved it thanks to this comment https://github.com/grand-stack/graphql-auth-directives/issues/4#issuecomment-494620480
const server = new ApolloServer({
schema,
context: ({ req }) => {
return {
headers: req.headers,
driver
};
}
});
and it did work.

AWS Cognito with Angular 4: Error: Missing region in config

I'm developing a web application which uses AWS services backend size.
In this moment I use AWS Cognito to manage user sessions.
I'm developing the application with Angular 4 (using TypeScript / JavaScript language) and I found this useful class (In the JavaScript SDK for AWS Cognito) that should provide me with so many data that I need to display on the frontend:
http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/CognitoIdentityServiceProvider.html
The problem is that any method I invoke on this object, the console return this error:
Error: Missing region in config
at Request.VALIDATE_REGION (event_listeners.js:91)
at Request.callListeners (sequential_executor.js:105)
at callNextListener (sequential_executor.js:95)
at event_listeners.js:85
at finish (config.js:315)
at Config.getCredentials (config.js:360)
at Request.VALIDATE_CREDENTIALS (event_listeners.js:80)
at Request.callListeners (sequential_executor.js:101)
at Request.emit (sequential_executor.js:77)
at Request.emit (request.js:683)
I do not understand why this happens, because I have correctly configured the region, like this:
//Setting AWS credentials
AWS.config.region = environment.region;
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
IdentityPoolId : environment.identityPoolId
});
and if i use the instruction console.log(AWS.config.region), the console prints the correct region.
Why it continues to visualize that error?
The complete code:
var params = {
UserPoolId: environment.clientId,
};
//Setting AWS credentials
AWS.config.region = environment.region;
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
IdentityPoolId : environment.identityPoolId
});
this.cognitoidentityserviceprovider.listUsers(params, function(err, data) {
console.log(AWS.config.region)
if (err) console.log(err); // an error occurred
else console.log(data); // successful response
});
the path is always console.log(err) and the error is always Missing region in config. Why does this continue to happen?
How about if you do:
var CognitoIdentityServiceProvider = AWS.CognitoIdentityServiceProvider;
var client = new CognitoIdentityServiceProvider({ apiVersion: '2016-04-19', region: 'us-east-1' });
and you call listUsers on the client object? I believe region should be passed along when you initialize the service client.
This question is from a while ago, but this worked for me:
When you load the AWS SDK in order to create the AWS instance, you probably have to set the region there, like this:
const AWS = require('aws-sdk');
AWS.config.update({
region: 'us-west-1',
});
function(){
var identityService = new AWS.CognitoIdentityServiceProvider({
apiVersion: '2016-04-18'
});
...
}
Note that you might also have to set your credentials, depending on the action. In this case, you can use code like this:
const AWS = require('aws-sdk');
AWS.config.update({
region: 'us-west-1',
accessKeyId: process.env.YOUR_ACCESSKEY,
secretAccessKey: process.env.YOUR_SECRETKEY
});
function(){
var identityService = new AWS.CognitoIdentityServiceProvider({
apiVersion: '2016-04-18'
});
...
}

Categories