AWS IoT policy doesn't restrict access - amazon-web-services

I am trying to restrict access to my AWS IoT devices with a Policy, but my policy doesn't seem to do that. It still lets me do whatever I want to the device. The policy is practically useless. To test this, I removed the following action.
{
"Effect": "Allow",
"Action": "iot:UpdateThingShadow",
"Resource": "arn:aws:iot:us-east-1:**********:thing/${iot:Connection.Thing.ThingName}"
}
So now my policy is this:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "iot:GetThingShadow",
"Resource": "arn:aws:iot:us-east-1:**********:thing/${iot:Connection.Thing.ThingName}"
}
]
}
However, when I try to update my thing shadow like so:
var params = {
thingName: "bar",
payload: JSON.stringify({ // payload is in string form according to docs
"state": {
"desired": {
"state": 0
}
}
})
};
await iotdata.updateThingShadow(params, function (err, data) {
if (err){
}
else{
}
});
... it still updates my device's shadow. My policy says it can't do that though! How can I get my policy to work?

In my experience,
It takes some minutes to apply completely.
I think you changed your policy and then run your test code ASAP. right?

Related

How can I upload images to s3 in react native?

I am trying to upload local images from my react native app (i'm using expo) to an s3 bucket, but nothing seems to work.
I'm am using react-native-aws3 library, but Promise.then never gets called. It doesn't throw any error either.
This is the code:
const options = {
bucket: BUCKET_NAME,
region: REGION,
accessKey: AWS_USER_KEY,
secretKey: AWS_PRIVATE_KEY,
successActionStatus: 201
}
export async function uploadImage(imageUri, imageName, imageType) {
const file = {
uri: imageUri,
name: imageName,
type: "image/" + imageType
}
RNS3.put(file, options).then( (response) => {
console.log("done")
console.log(response)
console.log(response.status)
})
}
This is the Bucket Policy:
{
"Version": "2012-10-17",
"Id": "Policy1648118554991",
"Statement": [
{
"Sid": "Stmt1648118551643",
"Effect": "Allow",
"Principal": "*",
"Action": [
"s3:GetObject",
"s3:PutObject",
"s3:ListBucket"
],
"Resource": [
"arn:aws:s3:::BUCKET_NAME",
"arn:aws:s3:::BUCKET_NAME/*"
]
}
]
}
This is the IAM user policy:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "VisualEditor0",
"Effect": "Allow",
"Action": [
"s3:PutObject",
"s3:PutObjectAcl"
],
"Resource": "arn:aws:s3:::BUCKET_NAME/*"
}
]
}
I tried following every tutorial I could find, but nothing seems to work. Do I have to do something else, like server side? or is there something wrong in the policies?
To upload content to an Amazon S3 bucket, use the official AWS SDK for JavaScript. To use this SDK with React, look at this doc topic:
Getting started in React Native
To work with Amazon S3, see:
Amazon S3 examples
code mentioned here works in "react-native": "0.68.2"
your react native camera collects image uri something like this file:///storage/emulated/0/Android/data/com.lobb.agent/files/Pictures/image-e4047ca8-5df9-489d-ac86-2bcdf24cd3436728860500254451478.jpg
following code does these steps
accepts your image uri
convert the image uri in to blob,
makes put request to s3 bucket
const handleImageUpload = async () => {
try {
const resp = await fetch(yourImageURI); //
const imageBody = await resp.blob(); // conv uri to blob
const result = await fetch(yourSignedURL, {
method: 'PUT',
body: imageBody,
});
console.log('result:', result);
} catch (error) {
console.log('error upload :', error);
}
};

Appsync Query Returning Null with Cognito Auth

I'm trying to do some appsync in the console using a userpool user who is a part of the group.
However, my query is returning null in the response.
The below PK in my query definitely exists.
I suspect that the issue is related to cognito. I can't pin it down exactly. The user I am testing is in the customers group and I am not receiving an error there due to cognito group permissions.
Logs are not helpful.
If I create a new API in the console (using an API key rather than cognito for auth) and import the dynamodb table (using the same role), the same query returns data.
Do I need to give my cognito group a role that allows them to interact with appsync?
My query:
query MyQuery {
getTable(PK: "PRODUCT#cb699976-153c-4852-a455-bc9a7bce6a93", SK: "PRODUCT#BLEND") {
DK1
PK
SK
}
}
The response:
{
"data": {
"getTable": null
}
}
The Schema:
type Query {
getTable(PK: String!, SK: String!): Table
#aws_auth(cognito_groups: ["customers"])
}
type Table #aws_auth(cognito_groups: ["customers"]) {
DK1: String
PK: String!
SK: String!
}
iam role for dynamodb (least permission access is still todo)
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "",
"Effect": "Allow",
"Action": "dynamodb:*",
"Resource": [
"arn:aws:dynamodb:us-east-1:blah_account:table/blah_table/index/GSI1",
"arn:aws:dynamodb:us-east-1:blah_account:table/blah_table"
]
}
]
}
appsync role trust relationship
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "",
"Effect": "Allow",
"Principal": {
"Service": "appsync.amazonaws.com"
},
"Action": "sts:AssumeRole"
}
]
}
appsync config ($ aws appsync get-graphql-api):
{
"graphqlApi": {
"name": "blah_dev_appsync",
"apiId": "blah",
"authenticationType": "AMAZON_COGNITO_USER_POOLS",
"userPoolConfig": {
"userPoolId": "us-east-1_blah",
"awsRegion": "us-east-1",
"defaultAction": "DENY"
},
"arn": "arn:aws:appsync:us-east-1:blah_id:apis/blah_",
"xrayEnabled": false
}
}
Can you check if there is a resolver attached to your (failing) Appsync API ?
If you have access to the web console look for this screen:
If there is nothing attached to getTable then that's probably why you are having null answers.
Resolvers Docs
Thanks to Ivan Caracamo's response, I learned that I needed to properly configure my resolvers.
I was able to get there with the resolver docs and this post.
Here's my request template
{
"version": "2017-02-28",
"operation": "GetItem",
"key": {
"PK": $util.dynamodb.toDynamoDBJson($ctx.args.PK),
"SK": $util.dynamodb.toDynamoDBJson($ctx.args.SK),
},
}
And here's my response template
$util.toJson($ctx.result)

AWS IAM policy restriction based on Tags not giving me any access

So I followed this AWS tutorial and created this IAM policy that should give access to any dynamodb action that has these keys. But as you can see in the image attached, it tells me I do not have any permission. Also it does happen to other services, so not only dynamodb, and also I tried to hardcode the 'access-project' tag in the policy as done with the 'access-environment as you can see.
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "AllActionsSameProjectEnvironment",
"Effect": "Allow",
"Action": "dynamodb:*",
"Resource": "*",
"Condition": {
"StringEquals": {
"aws:ResourceTag/access-project": "${aws:PrincipalTag/access-project}",
"aws:ResourceTag/access-environment": "pre"
},
"ForAllValues:StringEquals": {
"aws:TagKeys": [
"access-project",
"access-environment",
"Name",
"OwnedBy"
]
},
"StringEqualsIfExists": {
"aws:RequestTag/access-project": "${aws:PrincipalTag/access-project}",
"aws:RequestTag/access-environment": "pre"
}
}
}
]
}
error image
Any idea why is this happening? Thanks!
DynamoDB does not support Authorization based on tags as listed in the docs.

Unable to send data to SNS from lambda using designer vew

When following Introducing AWS Lambda Destinations I'm told to create an SNS as destination, I do that:
But it doesn't send anything. I had already an SNS able to send mail to my account, and I have adapted the policy to accept everything from everyone (it works with the 'Publish another message' button)
If I call the sns from code it works:
if (event.Success) {
console.log("Success");
context.callbackWaitsForEmptyEventLoop = false;
var sns = new AWS.SNS();
sns.publish({
Message: 'File(s) uploaded successfully',
TopicArn: 'arn:aws:sns:XXX:YYY:ZZZ'
}, (err,data) => {
if (err) {
console.log(err.stack);
return;
}
callback(null);
});
}
But I was hoping not having to write code for that (that what's suggested from the blog entry) so for example if I change the SNS topic I don't have to change the code.
Have any of you succeeded in doing this?
Thanks,
I have reviewed and replicated the AWS Lambda Destinations blog successfully without modifying the sample code snippet from the blog.
I would suggest, you review your SNS configuration (and change us-west-2 region to your AWS region of use as need be) and check if it matches the following:
1. On your SNS topic ('arn:aws:sns:us-west-2:1234567890:YourSNSTopicOnSuccess'), navigate to the access policy and check if you have a policy similar to the following :
{
"Version": "2008-10-17",
"Id": "__default_policy_ID",
"Statement": [
{
"Sid": "__default_statement_ID",
"Effect": "Allow",
"Principal": {
"Service": "lambda.amazonaws.com"
},
"Action": [
"SNS:GetTopicAttributes",
"SNS:SetTopicAttributes",
"SNS:AddPermission",
"SNS:RemovePermission",
"SNS:DeleteTopic",
"SNS:Subscribe",
"SNS:ListSubscriptionsByTopic",
"SNS:Publish",
"SNS:Receive"
],
"Resource": "arn:aws:sns:us-west-2:1234567890:YourSNSTopicOnSuccess"
}
]
}
2. On your Lambda role ('arn:aws:iam::1234567890:role/YourLambdaDestinationRole'), make sure of the following:
(i) The "Trust relationship" of your role has the following statement :
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service":"lambda.amazonaws.com"
},
"Action": "sts:AssumeRole"
}
]
}
(ii) The Lambda role has an attached policy document similar to one given below:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"sns:publish"
],
"Resource": "*"
}
]
}
The successful published message from Amazon Lambda to SNS topic should output something similar to:
{"version":"1.0","timestamp":"2020-03-22T16:29:50.528Z","requestContext":{"requestId":"43d109d2-54be-4e2e-b8d8-2757e3f06f76","functionArn":"arn:aws:lambda:eu-west-1:1234567890:function:event-destinations:$LATEST","condition":"Success","approximateInvokeCount":1},"requestPayload":{ "Success": true },"responseContext":{"statusCode":200,"executedVersion":"$LATEST"},"responsePayload":null}
Hope this helps.

AWS/Cognito/IAM Error with Unauth role

This message was originally posted on the AWS Developer Forums, but it seems like the AWS crowd is on SO, so I'm duplicating it here.
Hi there, I'm an absolute AWS beginner so I'll try to be as clear as possible.
I'm trying to use the JS API to allow any user on my site to upload videos to S3 (this works well) and then convert the uploaded files to other formats (with Elastic Transcoder).
I've set up:
an input (not public) and an output (public) buckets on S3. The input receives the user-submitted videos, that part works :)
an Elastic Transcoder pipeline (video-converter-test-pipeline-01)
a federated identity on Cognito (video_converter_test_02)
matching Auth and Unauth roles on IAM (Cognito_video_converter_test_02Auth_Role and Cognito_video_converter_test_02Unauth_Role)
The pipeline has the following permission summary: "The following IAM roles have been granted access to this pipeline: arn:aws:iam::529773801731:role/Elastic_Transcoder_Default_Role"
Cognito_video_converter_test_02Unauth_Role has two attached policies:
oneClick_Cognito_video_converter_test_02Unauth_Role_1522923667877
video-converter-policy, that I made myself.
Here's its JSON representation:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "VisualEditor0",
"Effect": "Allow",
"Action": "elastictranscoder:CreateJob",
"Resource": [
"arn:aws:elastictranscoder:*:*:pipeline/*",
"arn:aws:elastictranscoder:*:*:preset/*"
]
}
]
}
Here's how I try to create a transcoding job using the JS API:
function createJob(uploadedFileKey) {
console.log("Create job", uploadedFileKey);
var params = {
PipelineId: PipelineId,
Input: {
Key: uploadedFileKey
},
Output: {
PresetId: PresetId
}
};
elastictranscoder.createJob(params, function (err, data) {
if (err) console.error(err, err.stack); // an error occurred
else console.log(data); // successful response
});
}
When executing it, I get the following error:
Error: User: arn:aws:sts::529773801731:assumed-role/Cognito_video_converter_test_02Unauth_Role/CognitoIdentityCredentials is not authorized to perform: elastictranscoder:CreateJob on resource: arn:aws:elastictranscoder:eu-west-1:529773801731:pipeline/1522763370759-mmowmr
I tried using IAM Policy Simulator to understand what was wrong, but when doing so with the same parameters, I get "allowed"...
I'm sure I'm doing something wrong here, but can't understand what. I've tried many things but nothing worked. Any help would be appreciated :)
Thanks in advance, bye!
I contacted AWS Developer Support and the solution seems to be to have these in the IAM Policy:
{
"Sid": "VisualEditor3",
"Effect": "Allow",
"Action": "cognito-sync:*",
"Resource": "*"
},
{
"Sid": "VisualEditor3",
"Effect": "Allow",
"Action": "mobileanalytics:PutEvents",
"Resource": "*"
}