iothub-errorcode: InvalidProtocolVersion - node.js

Using the azure-iot-device sdk for node works in a standalone node program. When trying to use the same node code in a React web app, the connection to the IoT Hub fails "iothub-errorcode: InvalidProtocolVersion" with this error:
stream.js:61 WebSocket connection to 'wss://my-iothub.azure-devices.net/' failed: Error during WebSocket handshake: Unexpected response code: 400
App.js
var Protocol = require('azure-iot-device-mqtt').Mqtt;
var Client = require('azure-iot-device').Client;
var connectionString = "HostName=my-iothub.azure-devices.net;DeviceId=<redacted>;SharedAccessKey=<redacted>=";
var client = Client.fromConnectionString(connectionString, Protocol);
var connectCallback = function (err) {
if (err) {
console.error('Could not connect: ' + err.message);
}
...
};
client.open(connectCallback);
Headers (From Chrome dev tools)
Request URL: wss://my-iothub.azure-devices.net/
Request Method: GET
Status Code: 400 Bad Request
Content-Length: 158
Content-Type: application/json; charset=utf-8
Date: Wed, 02 Oct 2019 21:18:10 GMT
iothub-errorcode: InvalidProtocolVersion
Server: Microsoft-HTTPAPI/2.0
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Cache-Control: no-cache
Connection: Upgrade
Host: my-iothub.azure-devices.net
Origin: http://localhost:3000
Pragma: no-cache
Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits
Sec-WebSocket-Key: <redacted>
Sec-WebSocket-Protocol: mqtt
Sec-WebSocket-Version: 13
Upgrade: websocket
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_0)
Possibly related to: https://github.com/Azure/azure-sdk-for-js/issues/3473#issuecomment-499719031

I am assuming you are trying to utilise IOT hub from your react web app which is deployed in Microsoft Azure , if this is the case, please try the following:
what you need to check is the web app settings:
Set the consumer group as mentioned in this link.
Enable WebSocket.
Additional reference , please check the code repo and documentation around IOT HUB usage in web app, which is mentioned below:
https://learn.microsoft.com/en-us/azure/iot-hub/iot-hub-live-data-visualization-in-web-apps
https://github.com/Azure/azure-iot-sdk-node/blob/master/device/ts-samples/sample_device.ts

Related

Firebase Authentication 403 in production but works fine with localhost

Firebase authentication works just fine in localhost, but in a google cloud run project in production it fails with just a 403, no details of why the error
Here is the headers:
> POST /api/account/auth2/ HTTP/2 Host: appsite.com User-Agent: Mozilla/5.0
> (Macintosh; Intel Mac OS X 10.15; rv:95.0) Gecko/20100101 Firefox/95.0
> Accept: */* Accept-Language: en-US,en;q=0.5 Accept-Encoding: gzip,
> deflate, br Referer: https://appsite.com/ Content-Type:
> application/x-www-form-urlencoded; charset=UTF-8 X-CSRFToken:
> 6cpDY8qOBRK9XqfWcuLX6eujG85AmOnHp...b5f0j0t7tHy5rmAWCcEDw
> X-Requested-With: XMLHttpRequest Content-Length: 1251 Origin:
> https://appsite.com Connection: keep-alive Cookie:
> csrftoken=6cpDY8qOBRK9XqfWcuLX6eujG85AmOnHpi4IR9rRd...Hy5rmAWCcEDw
> Sec-Fetch-Dest: empty Sec-Fetch-Mode: cors Sec-Fetch-Site: same-origin
> TE: trailers
And yes I have the domain name added in the firebase auth domains.
Any help here will be great.
I am using the google gloud python google-auth=2.3.3
decoded_token = auth.verify_id_token(token)
uid = decoded_token["uid"]
And my Javascript: const provider = new
firebase.auth.GoogleAuthProvider();
$('.googleLogin').click(async function () {
const provider = new firebase.auth.GoogleAuthProvider();
// [START auth_google_provider_scopes]
const credential = await firebase.auth().signInWithPopup(provider);
const idToken = await firebase.auth().currentUser.getIdToken();
// Send Token to Back End
return handleMethod(idToken)
});
This was a CSRF verification failed.
I had to use postman to figure out what was happening.
In case someone else faces the same problem.
Forbidden (403)
CSRF verification failed. Request aborted.

DocuSign_eSign::ApiError: Bad Request

I'm using the Docusign Ruby SDK to make calls on the API. I have my code working when pointed to the developer docusign, when pointed to prod I'm getting the DocuSign_eSign::ApiError: Bad Request error.
I have already gotten my integration key/client id approved in production and I've also already done the authorization grant part, where you allow the integration key to send envelopes on a user's behalf. This has been done in dev and production.
desc 'Perform API call to list envelopes'
task list: :initialize do
options = DocuSign_eSign::ListStatusChangesOptions.new
options.from_date = (Date.today - 10).strftime('%Y/%m/%d')
options.status = 'completed'
#list_results = #envelopes_api.list_status_changes #account_id, options
end
desc 'Build list results hash'
task build_list_hash: :list do
#list_results_hash = []
#list_results.envelopes.each do |list_hash|
#list_results_hash << { envelope_id: list_hash.envelope_id, status: 'pending', archive_at: Time.now + (86400 *30) }
end
puts "List results hash:\n #{#list_results_hash}"
File.open(ENV['MASTER_LIST_FILE'], 'w') { |file| file.write(#list_results_hash.to_yaml) }
end
I expect the output to be a list of envelopes which is what happens when running on demo.docusign
Update: Thanks for showing me how to get logs. It seems the error is with GetUserProfileImage
GET https://na3-app.docusign.net:8832/restapi/v2.1/accounts/91608b5d-d418-4c45-89f0-cd088504f99d/users/63757e15-8365-4fb9-9e7d-d9a8309f8e94/profile/image
TraceToken: 996d3b3f-2857-47d6-9d75-26a75b6b0a37
Timestamp: 2019-10-17T20:58:32.0932823Z
Content-Length: 0
Connection: keep-alive
Accept: application/json;text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5
Accept-Encoding: gzipdeflatebr
Accept-Language: en-USen; q=0.5
Authorization: Bearer [omitted]
Host: na3-app.docusign.net
Referer: https://app.docusign.com/preferences/security
User-Agent: Mozilla/5.0(Windows NT 10.0; Win64; x64; rv:69.0)Gecko/20100101Firefox/69.0
x-docusign-clienttransactionid: fa4e1202-09a4-431b-9abf-fe4d00acf565
x-csrf-token: c34f42c5aad288063afc8a6615be03c9
x-forwarded-for: 170.140.186.226, 162.248.185.11
x-docusign-authentication: {"IntegratorKey":"[omitted]"}
x-docusign-prettyprint: false
content-transfer-encoding: base64
x-forwarded-for-martini: 170.140.186.226
x-docusign-diagnostics: {"storedProcedureEventLogThreshold":"300"}
x-docusign-timetrack: CONN_START,2019-10-17T20:58:31.946Z;;REQ_SENT,2019-10-17T20:58:31.950Z;REST0_Start,2019-10-17T20:58:32.0620315Z
x-docusign-correlationtoken: fa4e1202-09a4-431b-9abf-fe4d00acf565
X-SecurityProtocol-Version: TLSv1.2
X-SecurityProtocol-CipherSuite: ECDHE-RSA-AES256-GCM-SHA384
404 NotFound
Content-Type: application/json; charset=utf-8
Content-Length: 95
X-DocuSign-ClientTransactionId: fa4e1202-09a4-431b-9abf-fe4d00acf565
X-DocuSign-TimeTrack: CONN_START,2019-10-17T20:58:31.946Z;;REQ_SENT,2019-10-17T20:58:31.950Z;;REST0_Start,2019-10-17T20:58:32.0620315Z;REST0_End,2019-10-17T20:58:32.0932823Z
X-DocuSign-TraceToken: 996d3b3f-2857-47d6-9d75-26a75b6b0a37
{"errorCode":"RESOURCE_NOT_FOUND","message":"The URL provided does not resolve to a resource."}```

Getting the API Key from ServiceStack request

Have a simple get Customer api that's returning list of customers fine.
Setting up for service to service authentication, if I make this [Authenticated] and try to implement using ApiKeyAuthProvider, the req.GetApiKey returns null and I get an error;
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request starting HTTP/1.1 POST https://localhost:44347/api/customers application/json 0
Microsoft.AspNetCore.Hosting.Internal.WebHost:2019-07-01 16:50:34,004 [16] INFO Microsoft.AspNetCore.Hosting.Internal.WebHost - Request starting HTTP/1.1 POST https://localhost:44347/api/customers application/json 0
The thread 0x42cc has exited with code 0 (0x0).
The thread 0x302c has exited with code 0 (0x0).
ServiceStack.ServiceStackHost:2019-07-01 17:01:14,601 [16] ERROR ServiceStack.ServiceStackHost - ServiceBase<TRequest>::Service Exception
System.ArgumentOutOfRangeException: Length cannot be less than zero.
Parameter name: length
at System.String.Substring(Int32 startIndex, Int32 length)
at ServiceStack.Host.HttpRequestAuthentication.GetBasicAuth(IRequest httpReq) in C:\BuildAgent\work\3481147c480f4a2f\src\ServiceStack\Host\HttpRequestAuthentication.cs:line 45
at ServiceStack.Host.HttpRequestAuthentication.GetBasicAuthUserAndPassword(IRequest httpReq) in C:\BuildAgent\work\3481147c480f4a2f\src\ServiceStack\Host\HttpRequestAuthentication.cs:line 50
at ServiceStack.Auth.ApiKeyAuthProvider.PreAuthenticate(IRequest req, IResponse res) in C:\BuildAgent\work\3481147c480f4a2f\src\ServiceStack\Auth\ApiKeyAuthProvider.cs:line 232
at ServiceStack.AuthenticateAttribute.PreAuthenticate(IRequest req, IEnumerable`1 authProviders) in C:\BuildAgent\work\3481147c480f4a2f\src\ServiceStack\AuthenticateAttribute.cs:line 96
at ServiceStack.AuthenticateAttribute.ExecuteAsync(IRequest req, IResponse res, Object requestDto) in C:\BuildAgent\work\3481147c480f4a2f\src\ServiceStack\AuthenticateAttribute.cs:line 74
at ServiceStack.Host.ServiceRunner`1.ExecuteAsync(IRequest req, Object instance, TRequest requestDto) in C:\BuildAgent\work\3481147c480f4a2f\src\ServiceStack\Host\ServiceRunner.cs:line 127
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request finished in 640574.8754ms 400 application/json; charset=utf-8
Microsoft.AspNetCore.Hosting.Internal.WebHost:2019-07-01 17:01:14,607 [16] INFO Microsoft.AspNetCore.Hosting.Internal.WebHost - Request finished in 640574.8754ms 400 application/json; charset=utf-8
Clearly I have missed something obvious...any pointers appreciated.
// Register ORMLite connection
container.Register<IDbConnectionFactory>(dbFactory);
//Tell ServiceStack you want to persist User Auth Info in SQL Server
container.Register<IAuthRepository>(c => new OrmLiteAuthRepository(dbFactory));
// See https://docs.servicestack.net/api-key-authprovider
Plugins.Add(new AuthFeature(() => new AuthUserSession(),
new IAuthProvider[] {
new ApiKeyAuthProvider(AppSettings) {
SessionCacheDuration = TimeSpan.FromMinutes(10),
AllowInHttpParams = true, // Whether to allow API Keys in 'apikey' QueryString or FormData (e.g. `?apikey={APIKEY}`)
RequireSecureConnection = true,
},
}
) {
IncludeRegistrationService = true,
});
GlobalRequestFilters.Add((req, res, dto) =>
{
LastApiKey = req.GetApiKey();
});
Request
POST https://localhost:44347/api/customers HTTP/1.1
Host: localhost:44347
Connection: keep-alive
Content-Length: 2
Accept: application/json
Origin: https://localhost:44347
Authorization: yDOr26HsxyhpuRB3qbG07qfCmDhqutnA-yDOr26HsxyhpuRB3qbG07qfCmDhqutnA-yDOr26HsxyhpuRB3qbG07qfCmDhqutnA
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36
Content-Type: application/json
Referer: https://localhost:44347/swagger-ui/
Accept-Encoding: gzip, deflate, br
Accept-Language: en-GB,en;q=0.9,en-US;q=0.8
{}
Response
HTTP/1.1 400 ArgumentOutOfRangeException
Transfer-Encoding: chunked
Content-Type: application/json; charset=utf-8
Vary: Accept,Origin
Server: Microsoft-IIS/10.0
X-Powered-By: ServiceStack/5.50 NetCore/Windows
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, PUT, DELETE, PATCH, OPTIONS
Access-Control-Allow-Headers: Content-Type
X-Startup-Errors: 1
Access-Control-Allow-Credentials: true
Access-Control-Expose-Headers: Content-Disposition
X-SourceFiles: =?UTF-8?B?QzpcUmVwb3NcTUJXZWJccnZhcGlcUnZXZWJcUnZBcGlcYXBpXGN1c3RvbWVycw==?=
X-Powered-By: ASP.NET
Date: Wed, 03 Jul 2019 08:07:40 GMT
13e
{"responseStatus":{"errorCode":"ArgumentOutOfRangeException","message":"Length cannot be less than zero.\r\nParameter name: length","errors":[{"errorCode":"ArgumentOutOfRangeException","fieldName":"length","message":"Length cannot be less than zero.\r\n"}]},"responseCreatedUtcDateTime":"2019-07-03T08:07:40.7955827Z"}
0
Your client is sending an invalid Authorization Bearer Token, it needs to have the Authroization Bearer Token format:
Authorization: Bearer {Token}
If you're sending an Authenticated API Key or JWT Request via Open API it needs to have the Bearer prefix as per the Open API docs:
OK I had manually created a User and APIKey in the underlying tables and had used a UserAuthId 'SomeAuthId' i.e. letter in them, and the ORM repository code is expecting these to be integers. Its cool that I can see the code in github and debug this myself - thanks for the comment as it got me thinking and looking into my Auth setup.

D2C message using IoT Hub

I’d like to ask you a favor. I do have a problem confirming previously readed D2C message using IoT Hub. I am using REST API to pick up message like (I have replace SIG)
Request:
GET https://iot-hub-pospa.azure-devices.net/devices/18596c88-01e6-3f16-427b-10028d7305c5/messages/devicebound?api-version=2015-08-15-preview HTTP/1.1
IoTHub-MessageLockTimeout: 3600
Accept: application/json
Authorization: SharedAccessSignature sr=iot-hub-pospa.azure-devices.net&sig={sig}&se=1485558838&skn=iothubowner
Host: iot-hub-pospa.azure-devices.net
If-None-Match: "1c5006a4-2288-4a2f-b7ea-dcdf9b5bbc99"
Connection: Close
X-P2P-PeerDist: Version=1.1
X-P2P-PeerDistEx: MinContentInformation=1.0, MaxContentInformation=2.0
Accept-Encoding: peerdist
Response:
HTTP/1.1 200 OK
Content-Length: 35
ETag: "dfc78580-d251-4156-a5f6-c2a30811a504"
Server: Microsoft-HTTPAPI/2.0
iothub-messageid: 02cdb012-9749-48a9-bfb3-5812a4740675
iothub-to: /devices/18596c88-01e6-3f16-427b-10028d7305c5/messages/deviceBound
iothub-expiry:
iothub-correlationid:
iothub-ack: full
iothub-sequencenumber: 56
iothub-enqueuedtime: 2/2/2016 9:57:34 AM
iothub-deliverycount: 0
Date: Tue, 02 Feb 2016 10:21:43 GMT
Connection: close
2/2/2016 10:57:34 AM - Test message
Then when confirming I am getting HTTP 412 like
Request:
DELETE https://iot-hub-pospa.azure-devices.net/devices/18596c88-01e6-3f16-427b-10028d7305c5/messages/devicebound/02cdb012-9749-48a9-bfb3-5812a4740675?api-version=2015-08-15-preview HTTP/1.1
Accept: application/json
If-Match: "02cdb012-9749-48a9-bfb3-5812a4740675"
Authorization: SharedAccessSignature sr=iot-hub-pospa.azure-devices.net&sig={sig}&se=1485558838&skn=iothubowner
Host: iot-hub-pospa.azure-devices.net
Content-Length: 0
Connection: Close
Response:
HTTP/1.1 412 Precondition Failed
Content-Length: 330
Content-Type: application/json; charset=utf-8
Server: Microsoft-HTTPAPI/2.0
iothub-errorcode: DeviceMessageLockLost
Date: Tue, 02 Feb 2016 10:21:49 GMT
Connection: close
 
{"Message":"ErrorCode:DeviceMessageLockLost;Message 02cdb012-9749-48a9-bfb3-5812a4740675 lock was lost for Device 18596c88-01e6-3f16-427b-10028d7305c5\r\nTracking Id:05994074a3664933a0910b5fc70e04e5-G:GatewayWorkerRole.6-B:1-P:cffe397b-f627-4435-bd54-48f5ba79c3ca-TimeStamp:02/02/2016 10:21:49\r\nErrorCode:DeviceMessageLockLost"}
 
 
Does anybody know what should I do to successfully confirm/delete message from IoT Hub, please? Thanks
static DeviceClient _deviceClient;
_deviceClient = DeviceClient.CreateFromConnectionString(<IoTHubURI>, TransportType.Http1);
public void SendMessage(IDictionary<string, object> dictionary)
{
Microsoft.Azure.Devices.Client.Message message = new Microsoft.Azure.Devices.Client.Message();
try
{
foreach (var r in dictionary)
{
message.Properties[r.Key] = r.Value.ToString();
}
_deviceClient.SendEventAsync(message);
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}

socketstream app throwing 404 not found

I'm trying to load the socketstream application with express and cors, which is throwing an error stating 404. All the project directories are available in browser but no contents.
var app = require('express')();
var ss = require('socketstream');
var cors = require('cors');
ss.client.define('main', {
view : 'app.html',
css : [],
code : [],
tmpl : '*'
});
app.use(cors());
app.get('/', function(req, res) {
res.serve('main');
});
ss.start(app.listen(port));
And this is the response in browser
Headers
Remote Address:"RemoteAddress":"Port"
Request URL:http://"RemoteAddress":"Port"/_serveDev/code/app/someFile.js?ts=1449057700740&pathPrefix=app
Request Method:GET
Status Code:404 Not Found
Request headers
Connection:keep-alive
Content-Length:76
Content-Type:text/html; charset=utf-8
Date:Wed, 02 Dec 2015 12:03:20 GMT
X-Content-Type-Options:nosniff
X-Powered-By:Express
Response headers
Accept:*/*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8
Cache-Control:max-age=0
Connection:keep-alive
Host:"RemoteAddress":"Port"
Referer:http://"RemoteAddress":"Port"/
User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36
Update
The app.html is getting loaded in browser but 404 is only for scripts and css that is being requested from app.html.
Thanks.
Try to change the permissions of the files by running
sudo chmod 777 -R *
in the code directory.

Resources