AWS Appsync Http resolver for IOT device shadow - amazon-web-services

Im trying (in vain) to get a device shadow through appsync Http resolvers.
{
"version": "2018-05-29",
"method": "GET",
"resourcePath": "/things/${ctx.args.id}/shadow",
"params":{
"headers":
$utils.toJson($utils.http.copyHeaders($ctx.request.headers))
}
}
All im managing to get as a response is "Credential should be scoped to correct service"
I can see that the Authorization header for the call contains
"Credential = ---/---/eu-west-1/appsync/aws4_request"
When i call GET "deviceShadow" it as REST in my application today (which works) the same values are
"Credential = ---/---/eu-west-1/iotdata/aws4_request"
So it seams like appsync is being set as the service and that is messing up the call?
Any tips how to get this working?

I think you'll need to add a role and IAM signing configuration to the Data Source. Perform the following steps with the AWS CLI.
Attach an IAM role to the data source that grants the appropriate permissions to call the IoT Device Shadow operations. I think it's iot:GetThingShadow for this example.
Add an IAM configuration section to the AWS AppSync Data Source. This is NOT the resolver template.
{
"endpoint": "https://<iot-endpoint>",
"authorizationConfig": {
"authorizationType": "AWS_IAM",
"awsIamConfig": {
"signingRegion": "eu-west-1",
"signingServiceName": "iot"
}
}
}
When AWS AppSync invokes your resolver, it will generate a SigV4 signature using the attached role and call the AWS IoT Device Shadow service. Try this out.

Related

Is it possible to auto enable AWS Config on addition of a new account to organisation?

AWS has auto-join/auto-enable recording of new resources and accounts in Security Hub, which I am happily using.
I wanted to enable the same kind of setting for AWS Config, which currently require manual setup for all new accounts of my organisation. However, I failed to find anything similar to aforementioned Security Hub feature in Config.
Am I missing it or is it currently not available out-of-box?
#Ido Van Orell I do not think there is a native feature in AWS Config but what you can leverage for this is CloudFormation stacksets.
Create a CloudFormation template that enables AWS Config. Deploy it as stackset with automatic deployment enabled. This should ensure that when a new account joins your org AWS Config is enabled.
If you are using AWS Control Tower by any chance, you also get an event when account is vended which you can run automation on the back off.
{
"detail-type": ["AWS Service Event via CloudTrail"],
"source": ["aws.controltower"],
"detail":
{
"eventName": ["CreateManagedAccount"],
"serviceEventDetails":
{ "createManagedAccountStatus": { "state": ["SUCCEEDED"] } },
},
}
Use AWS Config Aggregator's integration with AWS Organisations to get a single pane of glass view across all accounts and regions for org where Config is enabled. Refer this

How to get the list of repository from AWS CodeCommit using AWS REST API call in Postman tool?

I have to use AWS REST API to work with various cloud services. Initially, I'm trying in postman tool to fetch the list of repositories from AWS CodeCommit. I'm following this link https://docs.aws.amazon.com/codecommit/latest/APIReference/API_ListRepositories.html to accomplish my task. I have problem on setting the authorization for this API call. I have provided both access and secret keys and the region. I could not get the repository lists instead facing 503 network issue.
UPDATE
I'm facing the following error message
{
"Output": {
"__type": "com.amazon.coral.service#UnknownOperationException"
},
"Version": "1.0"
}
In Postman, select the POST method and put URL as 'https://codecommit.us-east-1.amazonaws.com/'
Go to Headers and add
'Content-Type' key and 'application/x-amz-json-1.1' as the value
'X-Amz-Target' key and 'CodeCommit_20150413.ListRepositories' as the value
'Host' key and 'codecommit.us-east-1.amazonaws.com' as the value
Go to the 'Authorization' tab and configure the AWS Signature type as follows:
AccessKey: xxxxxxxxxxxxx
SecretKey: xxxxxxxxxxxxx
AWS Region: us-east-1
Go to 'Body' tab and type {}
Click 'Send' to test
Note: Make sure to use correct region in all the place above (us-east-1 as example).

How to know who started or stopped EC2 instance using AWS Serverless application

We have developed an AWS Serverless Lambda application using dotnetcore to perform operations on EC2 Instances, say start or stop EC2 instance and integrated with Aws API Gateway.
serverless.template in dotnetcore application
"StartInstanceById" : {
"Type" : "AWS::Serverless::Function",
"Properties": {
"Handler": "EC2_Monitoring_Serverless::EC2_Monitoring_Serverless.Functions::StartInstanceById",
"Runtime": "dotnetcore2.1",
"CodeUri": "",
"MemorySize": 256,
"Timeout": 30,
"Role": "arn:aws:iam::2808xxxx1013:role/lamda_start_stop",
"Policies": [ "AWSLambdaBasicExecutionRole" ],
"Events": {
"PutResource": {
"Type": "Api",
"Properties": {
"Path": "/instances",
"Method": "Get"
}
}
}
}
}
The above Lambda function is working fine for starting ec2 instance when I invoking the API gateway url.
For calling these API's, We have created Angular 6 application and provided authentication using Aws Cognito Userpools.
So the cognito user logins into the website and gets all EC2 informations.
If the user wants to stop / start the EC2 instance, user will click on the particular button which invokes the relevant api gateway url of the lambda functions and It's working fine.
Now the question is who performed that action. After so much of research on stackoverflow and aws community forums for knowing who started or stopped the EC2 instances , I found Aws CloudTrail logs the information when user start or stopped the instance.
So I created a trail and I can see the logs in S3 buckets. But in every log I opened, I saw that the role "arn:aws:iam::2808xxxx1013:role/lamda_start_stop" is captured. I know this is because of the Lambda function. But I want to know who really stopped the instance.
Please advice how to capture user details!
The reason lambda execution role is getting printed in cloudtrail, is because it has initiated the process to stop the ec2 instance. Here the role is assumed (instead of actual user).
To print your actual user, you need to implement logs at your lambda, which will print logs to Cloudwatch. You can get the actual user or any other custom information from those logs.

AWS APIGateway Lambda proxy integration- Execution failed due to configuration error: Invalid permissions on Lambda function

I am relatively new to AWS and the beast. After working on API Gateway to Lambda proxy integration I am getting Execution failed due to configuration error: Invalid permissions on Lambda function
I followed below setup referred from really well documented terraform documentation and does exactly what was needed for me. But while testing on API Gateway console giving the above error.
resource "aws_lambda_permission" "apigw" {
statement_id = "AllowAPIGatewayInvoke"
action = "lambda:InvokeFunction"
function_name = "${aws_lambda_function.resource_name.arn}"
principal = "apigateway.amazonaws.com"
# The /*/* portion grants access from any method on any resource
# within the API Gateway "REST API".
source_arn = "${aws_api_gateway_deployment.resource_name_of_deployment.execution_arn}/*/*"
}
Few learnings from API Gateway Lambda proxy integration
API Gateway is deployed in different stages and ARN for API gateway in stage vs on test console is somewhat different. (atleast thats what I got on terraform output)
As many documentations and fixes for the problem suggests to explicitly configure detailed path as "arn:aws:execute-api:region_name:account_id:${aws_api_gateway_rest_api.api_resource.id}/*/*"
The configured source with granted access permission
arn:aws:execute-api:region:accountid:fu349z93pa/*/*
From terraform documentation
For "${aws_api_gateway_deployment.deployment_rsc_name.execution_arn}"
The configured source with granted access permission is
arn:aws:execute-api:region:accountid:fu349z93pa/stage/*/*
If you test from API Gateway console you would end up with same error and have to manually add permission to lambda or reselect lambda function name on method integration console (which does the same thing). That configures 2 API gateways to access Lambda. (one with /stage deployed ARN and other /*/METHOD/* - used for test console)
But if you test API gateway from ARN of stage environment on postman it works just as fine without any manual updates to infrastructure built with terraform. And in most cases that is the one that would matter.
Even after fixing first error manually / not second challenge is Malformed response from lambda
This one is fairly easy and well documented. AWS Doc
All we have to do is update lambda to respond with a specified format.
for. e.g. add below
callback(null, { "statusCode": 200, "body" : JSON.stringify(sampleResponseJSON) }); on lambda `js`
Once it is working end to end we could always add error handling scenarios.
Hopefully, this should save some time for beginners like me.
So instead of using:
resource "aws_lambda_permission" "apigw" {
... ...
source_arn = "${aws_api_gateway_deployment.resource_name_of_deployment.execution_arn}/*/*"
}
I use the replace method to remove the stage_name from the execution_arn:
resource "aws_lambda_permission" "apigw" {
... ...
source_arn = "${replace(aws_api_gateway_deployment.resource_name_of_deployment.execution_arn, var.stage_name, "")}*/*"
}
And now everything works for me

AWS Cognito Post Authentication Lambda Trigger - groupConfiguration

Is it possible, via a post-authentication lambda to alter the list of groups exposed by the AWS Cognito Identity token?
The documentation for the post-authenticaion Lambda states the following:
"....
groupConfiguration structure – contains group-related information that can override group-related claims in the identity token."
Full docs: http://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-identity-pools-working-with-aws-lambda-triggers.html#cognito-user-pools-lambda-trigger-syntax-post-auth
The AWS Cognito Identity token exposes the current payload:
{
sub: "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
cognito:groups: [
"group1",
"group2"
],
iss: "https://cognito-idp.*****/**-****-1_********",
cognito:username: "Google_*****************",
.....
}
What I would like to to, via a post-authentication lambda is to alter the list of cognito-groups.
Any suggestions on how to do this?
There is a mixup in the documentation. This is not currently supported. We are actively working to fix it.