Connection to Azure Cosmosdb failed using web socket - azure-cosmosdb

I have a script that connects to CosmosDB to make some operations, am using CosmosDB as graphDB, however, am using a node module called gremlin-secure which connects to cosmosDB through web sockets, however, recently, I could not connect to the Database as below error
events.js:160
throw er; // Unhandled 'error' event
^
Error: unexpected server response (200)
at ClientRequest._req.on (/Users/abshahin/dev/azure-cosmos-db-graph-nodejs-getting-started/node_modules/ws/lib/WebSocket.js:656:26)
at emitOne (events.js:96:13)
at ClientRequest.emit (events.js:188:7)
at HTTPParser.parserOnIncomingClient [as onIncoming] (_http_client.js:473:21)
at HTTPParser.parserOnHeadersComplete (_http_common.js:99:23)
at TLSSocket.socketOnData (_http_client.js:362:20)
at emitOne (events.js:96:13)
at TLSSocket.emit (events.js:188:7)
at readableAddChunk (_stream_readable.js:176:18)
at TLSSocket.Readable.push (_stream_readable.js:134:10)
my code looks like this
"use strict";
var Gremlin = require('gremlin-secure');
var config = require("./config");
const client = Gremlin.createClient(
443,
config.endpoint,
{
"session": false,
"ssl": true,
"user": `/dbs/${config.database}/colls/${config.collection}`,
"password": config.primaryKey
});
client.execute("g.addV('employee').property('id', 'abshahin')", { }, (err, results) => {
if (err) return console.error(err);
console.log(JSON.stringify(results));
});
and this is my config
var config = {}
config.endpoint = "xxxxxxxx.graphs.azure.com";
config.primaryKey = "super secret key";
config.database = "dbname"
config.collection = "collectionName"
module.exports = config;
I contacted Microsoft and they advised to post here, any help.

Check to make sure that the url of the db looks like xxx.graphs.azure.com the ulr displayed in the azure portal was not correct in my case.

This looks a bit similar to a problem I faced recently. Make sure you have latest OpenSSL version
openssl version -a
Azure CosmosDB enforces SSL/TLS 1.2 which is not supported by older versions of OpenSSL

Related

Why does my opentok method does not work in firebase?

I use a firebase function which executes OpenTok SDK when it is triggered. The function creates a session. I was able to create a session successfully on my local server, but when I put it in production – in firebase- following error occurs:
Error creating session: Error: Failed to createSession. Error: The request failed: Error: getaddrinfo EAI_AGAIN api.opentok.com:443
at createSessionCallback (/srv/node_modules/opentok/lib/opentok.js:1125:16)
at Request._callback (/srv/node_modules/opentok/lib/client.js:59:14)
at self.callback (/srv/node_modules/request/request.js:185:22)
at emitOne (events.js:116:13)
at Request.emit (events.js:211:7)
at Request.onRequestError (/srv/node_modules/request/request.js:877:8)
at emitOne (events.js:121:20)
at ClientRequest.emit (events.js:211:7)
at TLSSocket.socketErrorListener (_http_client.js:401:9)
at emitOne (events.js:116:13)
Other methods of this third party SDK like token generation also works on firebase but the method createSession fails. Can you help me please?
exports.dbUpdate = functions.database.ref('/test/{pushId}/text').onUpdate((change, context) => {
const beforeData = change.before.val(); // data before the write
const afterData = change.after.val();
if (beforeData == afterData) {
console.log("Text did not change");
return null;
}
opentok = new OpenTok("...", "...");
var sessionId;
opentok.createSession({
mediaMode: "routed"
}, function(error, session) {
if (error) {
console.log("Error creating session:", error)
token = "Failed";
} else {
sessionId = session.sessionId;
token = opentok.generateToken(sessionId);
}
});
return change.after.ref.parent.child('neuertest').set(token);
});
//The same code works on local server
The free Spark plan only allows for HTTP calls to Google services (see Cloud Functions on https://firebase.google.com/pricing/)
You’ll need to upgrade your plan to be able to run your function

Setting up HTTPS on Deno , with self signed certificate?

I was setting up a Deno server to handle HTTPS request, I used self signed certificates to do the job.
Used below code for this:
import { serveTLS } from "https://deno.land/std/http/server.ts";
const body = new TextEncoder().encode("Hello HTTPS");
const options = {
hostname: "localhost",
port: 443,
certFile: "./path/to/localhost.crt",
keyFile: "./path/to/localhost.key",
};
// Top-level await supported
for await (const req of serveTLS(options)) {
req.respond({ body });
}
I ran this code as: deno --allow-net --allow-read app.ts
I get following error:
ERROR RS - rustls::session:571 - TLS alert received: Message {
typ: Alert,
version: TLSv1_3,
payload: Alert(
AlertMessagePayload {
level: Fatal,
description: BadCertificate,
},
),
}
error: Uncaught InvalidData: received fatal alert: BadCertificate
► $deno$/errors.ts:57:13
at InvalidData ($deno$/errors.ts:135:5)
at constructError ($deno$/errors.ts:57:13)
at unwrapResponse ($deno$/dispatch_json.ts:41:12)
at sendAsync ($deno$/dispatch_json.ts:96:10)
Is it possible to use self signed certificates with Deno ?
What went wrong and how to fix it ?
It was a problem with my certificate files, strangly the same certificates were working with nodejs.
I created local certificates and key than using this mkcert, then it worked!
If you're on MacOS, the best way to fix this is to instruct Deno to look at the system as the CA store.
Run this, then try again to see if you still get a warning/error:
export DENO_TLS_CA_STORE=system
You probably also want this in your .bash_profile as well.

Unable to call watson language translator using proxy

when I called watson language translator service over a public network its responded with no error. meanwhile, its not able to get response body over my private network
I am using the NGINX has my load balancer and have configure a proxy_http for it on the configuration.
The error is
{ Error: Response not received. Body of error is HTTP ClientRequest object
at formatError (root\node_modules\ibm-cloud-sdk-core\lib\requestwrapper.js:115:17)
at D:\Rafiki Project\production build\Rafiki Production Files 1\ecobot-orchestrator-master_23_9-orch_persistency_fixes\node_modules\ibm-cloud-sdk-core\lib\requestwrapper.js:265:19
at process._tickCallback (internal/process/next_tick.js:68:7)
var languageTranslator = new LanguageTranslatorV2({
username:'8******************',
password:'*************',
url: 'https://gateway.watsonplatform.net/language-translator/api/',
version: '2017-05-26'
});
function translateToWSPLan(req, res, callback){
console.log("the request for translation is::");
console.log(JSON.stringify(req));
console.log("======================");
languageTranslator.identify(req.body.identifyParams, function(err, data){
if(err){
console.log('=================error==========');
console.log(err);
console.log('=================================');
var errorLog = {name: err.name, message: err.message};
callback(errorLog);
}else {
}
})
See this issue raised on the Node.js SDK for Watson - https://github.com/watson-developer-cloud/node-sdk/issues/900#issuecomment-509257669
To enable proxy routing, add proxy settings to the constructor
var languageTranslator = new LanguageTranslatorV2({
username:'8******************',
password:'*************',
url: 'https://gateway.watsonplatform.net/language-translator/api/',
version: '2017-05-26',
// other params...
proxy: '<some proxy config>',
httpsAgent: '<or some https agent config>'
});
If you take a look at the issue, then there is a problem with accessing IAM tokens which does not work when there is a proxy, but as you appear to be using a userid / password combination, you should be OK. That is until cloud boundary style credentials are suspended and superseded by IAM credentials for all existing Watson services.

Unable to access URLs other than googleapis.com from Firebase emulator using fetch()

I'm trying to create some Firebase Cloud Functions and test them locally using
firebase emulators:start --only functions
These functions supposed to call some external services using fetch.
I find that I can call these external services when the functions are deployed to the Firebase cloud, but cannot invoke them when running locally in the emulator:
import 'cross-fetch/polyfill';
export const fetchTest = functions
.region(config.firebaseRegion)
.https.onRequest((request: Request, response: Response) => {
fetch("https://www.wikipedia.org/", {
method: 'GET',
}).then(value => {
console.log("Fetched: ", value);
}).catch(reason => {
console.log("Fetch failed: ", reason);
});
fetch("https://googleapis.com/foo", {
method: 'GET',
}).then(value => {
console.log("Fetched: ", value);
}).catch(reason => {
console.log("Fetch failed: ", reason);
});
response.send("Done");
});
This is the output I get when invoking fetchTest in the emulator:
⚠ Unknown network resource requested!
- URL: "https://www.wikipedia.org/"
⚠ Google API requested!
- URL: "https://googleapis.com/foo"
- Be careful, this may be a production service.
Looking at the source code there seems to be some filtering implemented in the emulator:
https://github.com/firebase/firebase-tools/blob/0586ee1e23adc64b0fe8607a026ba472a6bd7d2e/src/emulator/functionsEmulatorRuntime.ts
if (href && !history[href]) {
history[href] = true;
if (href.indexOf("googleapis.com") !== -1) {
new EmulatorLog("SYSTEM", "googleapis-network-access", "", {
href,
module: bundle.name,
}).log();
} else {
new EmulatorLog("SYSTEM", "unidentified-network-access", "", {
href,
module: bundle.name,
}).log();
}
}
Are there any reason for such restrictions? And is there a workaround for this?
Thanks!
When you see "Unknown network requested" logs like this one:
⚠ Unknown network resource requested!
- URL: "https://www.wikipedia.org/"
They are just warnings. The actual request is allowed through. The log is meant to tell you that the emulators are accessing resources outside your machine. This is normally something people want to avoid because local testing is meant to be hermetic, but sometimes it's what you want to do and you can ignore the warnings safely!

Firebase functions :ApiError: Not Found at Object.parseHttpRespBod : when removing from firebase storage

I'm trying to remove an item from my firebase storage by firebase cloud functions.
But its giving me this error..
Error { ApiError: Not Found
at Object.parseHttpRespBody (/user_code/node_modules/firebase-admin/node_modules/#google-cloud/common/src/util.js:193:30)
at Object.handleResp (/user_code/node_modules/firebase-admin/node_modules/#google-cloud/common/src/util.js:131:18)
at /user_code/node_modules/firebase-admin/node_modules/#google-cloud/common/src/util.js:496:12
at Request.onResponse [as _callback] (/user_code/node_modules/firebase-admin/node_modules/#google-cloud/common/node_modules/retry-request/index.js:198:7)
at Request.self.callback (/user_code/node_modules/firebase-admin/node_modules/request/request.js:185:22)
at emitTwo (events.js:106:13)
at Request.emit (events.js:191:7)
at Request.<anonymous> (/user_code/node_modules/firebase-admin/node_modules/request/request.js:1161:10)
at emitOne (events.js:96:13)
at Request.emit (events.js:188:7)
code: 404,
errors: [ { domain: 'global', reason: 'notFound', message: 'Not Found' } ],
response: undefined,
message: 'Not Found' }
And this is my code :
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
var db = admin.firestore();
var storage = admin.storage().bucket('visa_cop');
exports.deletingVisaCop = functions.firestore.document('users/{user_Id}/info/visa_cop').onUpdate((change,context) =>{
var data = change.after.data().checked;
if(data === true)
{
return storage.delete().then(function(data) {
return console.log("DataIs",data);
}).catch(function(error){
return console.log("Error",error);
});
} else
{
}
});
And I added for Google APIs Service Agent and App Engine default service account storage admin roles from the I am & admin page.
Thank You.
the problem is here:
functions.firestore.document('users/{user_Id}/info/visa_cop').onUpdate((change,context)
at the moment, the function listens to a document called "visa_cop" in the folder "info". you need to add the token at the end, to tell the function to listen to update of any file in this folder (or you can specify a file if needed).
Just append e.g. /{visaId} after visa_cop, like so:
functions.firestore.document('users/{user_Id}/info/visa_cop/{visaId}').onUpdate((change,context)
Ps. "visaId" can be anything, however it must match the Document Path that you define at function deploy.
in your example, the function listens to any doc in "visa_cop" folder, so if you use:
Console:
Trigger is "Cloud Firestore"
Event Type is "update"
Document Path is "students/{studentId}/visa_cop/{visaId}"
CLI:
gcloud functions deploy [FUNCTION_NAME] \
--runtime [RUNTIME] \
--trigger-event providers/cloud.firestore/eventTypes/document.update \
--trigger-resource "projects/[PROJECT_ID]/databases/(default)/documents/users/{userId}/info/visa_cop/{visaId}"

Resources