Cannot get simple AWS web socket publish to work - amazon-web-services

I wrote this uber simple client to publish a message to aws sdk via websocket protocol (javascript version). https://github.com/aws/aws-iot-device-sdk-js
var awsIot = require('aws-iot-device-sdk');
var device = awsIot.device({
region: "us-west-2",
protocol: "wss",
clientId: "ARUNAVS SUPER TEST",
host: "iot.us-west-2.amazonaws.com",
port: "443"
});
device
.on('connect', function() {
console.log('connect');
device.publish('abcd', JSON.stringify({ test_data: 1}));
});
device
.on('message', function(topic, payload) {
console.log('message', topic, payload.toString());
});
device
.on('error', function(error) {
console.log('error', error);
});
I am getting the following error (after importing admin creds https://github.com/aws/aws-iot-device-sdk-js#websockets):-
node testCode.js
error { Error: unexpected server response (403)
at ClientRequest._req.on
(/Users/arunavs/mrtests/node_modules/ws/lib/WebSocket.js:653:21)
at emitOne (events.js:96:13)
at ClientRequest.emit (events.js:188:7)
at HTTPParser.parserOnIncomingClient (_http_client.js:472:21)
at HTTPParser.parserOnHeadersComplete (_http_common.js:105:23)
at TLSSocket.socketOnData (_http_client.js:361:20)
at emitOne (events.js:96:13)
at TLSSocket.emit (events.js:188:7)
at readableAddChunk (_stream_readable.js:177:18)
at TLSSocket.Readable.push (_stream_readable.js:135:10)
type: 'error',
target:
WebSocket {
domain: null,
_events: {},
_eventsCount: 0,
_maxListeners: undefined,
readyState: 3,
bytesReceived: 0,
extensions: null,
protocol: '',
_binaryType: 'arraybuffer',
_finalize: [Function: bound finalize],
_closeFrameReceived: false,
_closeFrameSent: false,
_closeMessage: '',
_closeTimer: null,
_finalized: true,
The SDK fails to give any reason why I am getting a 403.
Note : According to https://github.com/aws/aws-iot-device-sdk-js/blob/234d170c865586f4e49e4b0946100d93f367ee8f/device/index.js#L142, the code is even presigning using sigv4, as part of my output also has
url: 'wss://iot.us-west-2.amazonaws.com:443/mqtt?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential= .......
Has anyone seen an error like this?

I think, you are publish on the THING which does not allow all users to connect with it.
Can you post the details of the policy of the thing that you are trying to publish message on.
On the Create a policy page, in the Name field, type a name for the
policy (for example, MyIoTButtonPolicy). In the Action field, type
iot:Connect. In the Resource ARN field, type *. Select the Allow
checkbox. This allows all clients to connect to AWS IoT.
Read more about POLICIES.
PS: This is just a wild guess. Please post policy details in the question so that I can be sure.

Related

AWS API Gateway -> Lambda -> Github Pages

I am trying to point a domain to Github pages site.
I am very new to working with domains and AWS services so I am finding it difficult to troubleshoot issues.
I have created an AWS ApiGateway that points to a lambda function which I would like to use to serve the content from Github pages, but currently, it is giving me the error:
{"message":"Internal Server Error"}
so when trying to fix this issue, I found instructions to make it log additional debug information. (instructions found at: https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-troubleshooting-lambda.html)
this is telling me that my configuration for the lambda function is incorrect.
The response from the Lambda function doesn't match the format that API Gateway expects. Lambda body contains the wrong type for field "headers"
I don't know what is expected so I don't know what needs to be changed... my entire lambda function is configured as:
exports.handler = async (event, context, callback) => {
let domain = 'https://github-org-name.github.io/my-repo-with-gh-pages/';
return {
statusCode: '301',
statusDescription: 'Moved Permanently',
headers: {
'location': [{
key: 'Location',
value: domain,
}],
'cache-control': [{
key: 'Cache-Control',
value: "max-age=3600"
}]
},
}
};
I am completely new to using AWS services, so I don't know if anything else needs to be configured. any help is appreciated.
The values in your headers dict must be strings, e.g:
{
"cookies" : ["cookie1", "cookie2"],
"isBase64Encoded": true|false,
"statusCode": httpStatusCode,
"headers": { "headername": "headervalue", ... },
"body": "Hello from Lambda!"
}
See the bottom of this page:
https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-develop-integrations-lambda.html

Unable to create a scheduler using the #google-cloud/scheduler package

GOT this error while creating a scheduler , earlier i got the code on local and it was working but when i deployed the code on vm on gcp itself it started failing and showed this error.
Error: 7 PERMISSION_DENIED: Request had insufficient authentication scopes.
at Object.callErrorFromStatus (/app/node_modules/#grpc/grpc-js/build/src/call.js:31:26)
at Object.onReceiveStatus (/app/node_modules/#grpc/grpc-js/build/src/client.js:180:52)
at Object.onReceiveStatus (/app/node_modules/#grpc/grpc-js/build/src/client-interceptors.js:336:141)
at Object.onReceiveStatus (/app/node_modules/#grpc/grpc-js/build/src/client-interceptors.js:299:181)`enter code here`
at /app/node_modules/#grpc/grpc-js/build/src/call-stream.js:160:78
at processTicksAndRejections (internal/process/task_queues.js:79:11) {
code: 7,
details: 'Request had insufficient authentication scopes.',
metadata: Metadata {
internalRepr: Map {
'google.rpc.errorinfo-bin' => [Array],
'grpc-status-details-bin' => [Array],
'grpc-server-stats-bin' => [Array]
},
options: {}
},
statusDetails: [
ErrorInfo {
metadata: [Object],
reason: 'ACCESS_TOKEN_SCOPE_INSUFFICIENT',
domain: 'googleapis.com'
}
],
reason: 'ACCESS_TOKEN_SCOPE_INSUFFICIENT',
domain: 'googleapis.com',
errorInfoMetadata: {
service: 'cloudscheduler.googleapis.com',
method: 'google.cloud.scheduler.v1.CloudScheduler.CreateJob'`enter code here`
}
}
If you use the default service account on your compute instance, you have to update the scopes; add all or only the Cloud Scheduler one.
If you don't use the default service account, you haven't scopes to select (scopes selection is a legacy mode, no longer available with new feature).
Note You have to stop the VM, change the scopes/service account and then restart the VM

Cannot connect DynamoDB with Lambda

Here is my code
var dynamodb = new AWS.DynamoDB();
dynamodb.batchGetItem(params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});
and I got this error
{
message: 'Could not load credentials from any providers',
errno: 'ETIMEDOUT',
code: 'CredentialsError',
syscall: 'connect',
address: 'x.x.x.x',
port: 80,
time: 2019-03-13T07:59:34.279Z,
originalError: {
errno: 'ETIMEDOUT',
code: 'ETIMEDOUT',
syscall: 'connect',
address: 'x.x.x.x',
port: 80,
message: 'connect ETIMEDOUT x.x.x.x:80'
}
}
I am new to AWS. I thought calling DynamoDB with Lambda do not need access and secret key. Is that correct?
I also grant full DynamoDB access permission role. What causes this problem?
I've faced the same problem here. The reason is your Lambda function seems inside a VPC and the DynamoDB isn't. Try removing the VPC in Network part of the settings and it should be solved.

AWS Appsync 401 and 403 errors in React Native

I've been pulling out my hair trying to set Appsync and Cognito in my React Native app.
I've tried the two following ways:
Amplify.configure(config);
OR
Amplify.configure({
Auth: {
region: config.aws_cognito_region, // REQUIRED - Amazon Cognito Region
userPoolId: config.aws_user_pools_id, // OPTIONAL - Amazon Cognito User Pool ID
userPoolWebClientId: config.aws_user_pools_web_client_id, // User Pool App Client ID
},
});
AND
const client = new AWSAppSyncClient({
url: appSyncConfig.graphqlEndpoint,
region: appSyncConfig.region,
auth: {
type: appSyncConfig.authType,
jwtToken: async () => (await Auth.currentSession()).getIdToken().getJwtToken(),
},
});
OR
const client = new AWSAppSyncClient({
url: appSyncConfig.graphqlEndpoint,
region: appSyncConfig.region,
auth: {
type: appSyncConfig.authType,
apiKey: appSyncConfig.apiKey,
},
});
I've also followed these two tutorials Tackling user auth, Building a notes app.
In both cases, I get the following error in GraphQL with no description:
Error: Network error: Response not successful: Received status code
This is while in Authorization Type is Amazon Cognito User Pool. I've also tried AWS Identity and Access Management (IAM), but that gives me a 403 error. Can someone point me in a direction where I can debug this further?
It might be caused a typo in the docs / article you've read. Trying replacing :
auth: {
type: appSyncConfig.authType,
apiKey: appSyncConfig.apiKey
}
with :
auth: {
type: appSyncConfig.authenticationType,
apiKey: appSyncConfig.apiKey
}
I have the following code and its working for me:
import Amplify, { Auth } from 'aws-amplify';
import API, { graphqlOperation } from '#aws-amplify/api'
window.LOG_LEVEL = 'DEBUG';
Amplify.configure({
Auth: {
"identityPoolId":'ap-southeast-1:xxxxxx',
"mandatorySignIn": false,
"region": "ap-southeast-1",
"userPoolId": "ap-southeast-1_xxxx",
"userPoolWebClientId": "xxxxxxx"
},
API:{
"aws_appsync_graphqlEndpoint": 'https://xxxx.ap-southeast-1.amazonaws.com/graphql',
"aws_appsync_region": 'ap-southwest-1',
"aws_appsync_authenticationType": 'AMAZON_COGNITO_USER_POOLS',
"aws_appsync_apiKey": 'null',
}
});

AWS Amplify React Native, GET request error 403 status code

I enabled access to unauthenticated identities to do some quick testing before integrating authentication. My configuration code is the following,
Amplify.configure({
Auth: {
identityPoolId: 'us-east-1:example',
region: 'us-east-1',
userPoolId: 'us-east-1_example',
userPoolWebClientId: 'us-east-1_example'
},
API: {
endpoints: [
{
name: "example-name",
endpoint: "https://example.execute-api.us-east-1.amazonaws.com/prod/example-path"
},
]
}
});
and my GET request code is the following,
example() {
const apiName = 'example-name';
const path = '/example-path';
API.get(apiName, path).then(response => {
console.log(response)
}).catch(error => {
console.log(error)
})
}
I followed everything on GitHub and my API gateway and Lambda functions are working correctly when I run a "test" and through postman. But on react-native it's giving me a 403 status code without any detailed explanation. Does this have to do with accessing using unauthenticated identity? Also, I used "example" in my code to hide my personal information, I typed in everything correctly since I'm not getting any syntax error (identity pool recognizes access every time I run it, but cloudWatch doesn't show any log of gateway access)
The Endpoint in Amplify.configure is the InvokeURL from API Gateway, you just need to include the stage (/prod in this case) and not the other routes. The other routes are just the path parameters for API.() calls.