proxy setting in adal-node package - node.js

I am trying to generate token to authenticate to Azure AD in my node server using adal-node package().Its working on my local machines but when trying to run on virtual machines its giving below error:
{
Error: getaddrinfo EAI_AGAIN login.microsoftonline.com login.microsoftonline.com:443
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:57:26)
errno: 'EAI_AGAIN',
code: 'EAI_AGAIN',
syscall: 'getaddrinfo',
hostname: 'login.microsoftonline.com',
host: 'login.microsoftonline.com',
port: 443` }
sample code snippet
var authorityUrl = 'https://login.microsoftonline.com/53d652a4-6f71-416f-971f-*****'
var applicationId = '26915ab6-22fc-4017-8741-***************'; // Application Id of app registered under AAD.
var clientSecret = '2NZtB5mIX1xZaXZ_I6I~-*********'; // Secret generated for app. Read this environment variable.
var resource = 'https://**************.com'; // URI that identifies the resource for which the token is valid.
var context = new AuthenticationContext(authorityUrl);
context.acquireTokenWithClientCredentials(resource, applicationId, clientSecret, function(err, tokenResponse) {
if (err) {
console.log('well that didn\'t work: ' + err.stack);
console.log(err);
res.json(err.stack);
} else {
console.log(tokenResponse.accessToken);
}
Analysis:It looks like proxy issue but unable to figure out how to set proxy url using adal-node package.Kindly suggest the way forward.

If you want to use the proxy server in your application, please refer to the following code
const { AuthenticationContext, Logging } = require("adal-node");
const proxy = require("node-global-proxy").default;
proxy.setConfig({
http: "",
https: ""
});
proxy.start();
const context = new AuthenticationContext(
"https://login.microsoftonline.com/const { AuthenticationContext, Logging } = require("adal-node");
const proxy = require("node-global-proxy").default;
proxy.setConfig({
http: "http://149.28.43.184:8080",
});
proxy.start();
const context = new AuthenticationContext(
"https://login.microsoftonline.com/e4c9ab4e-bd27-40d5-8459-230ba2a757fb"
);
Logging.setLoggingOptions({
log: function (level, message, error) {
console.log(message);
if (error) {
console.log(error);
}
},
loggingWithPII: false,
level: Logging.LOGGING_LEVEL.VERBOSE,
});
var applicationId = ""; // Application Id of app registered under AAD.
var clientSecret = ""; // Secret generated for app. Read this environment variable.
var resource = "";
context.acquireTokenWithClientCredentials(
resource,
applicationId,
clientSecret,
function (err, tokenResponse) {
if (err) {
console.log("well that didn't work: " + err.stack);
} else {
console.log(tokenResponse);
}
}
);
proxy.stop()

Related

Getting getaddrinfo ENOTFOUND when trying to connect to my AWS Neptune with node.js and gremlin

I am trying to connect to my Amazon Neptune instance from a API GW. I am using Node.js and Lambda
My YML looks like this
NeptuneDBCluster:
Type: "AWS::Neptune::DBCluster"
Outputs:
NeptuneEndpointAddress:
Description: Neptune DB endpoint address
Value: !GetAtt NeptuneDBCluster.Endpoint
Export:
Name: !Sub ${env:STAGE}-neptune-endpoint-address
My code looks like this
const gremlin = require('gremlin');
const {
NEPTUNE_ENDPOINT
} = process.env;
const { cardinality: { single } } = gremlin.process;
const DriverRemoteConnection = gremlin.driver.DriverRemoteConnection;
const Graph = gremlin.structure.Graph;
async function createUserNode(event, context, callback) {
const url = 'wss://" + NEPTUNE_ENDPOINT + ":8182/gremlin';
const dc = new DriverRemoteConnection(url);
const parsedBody = JSON.parse(event.body);
try {
const graph = new Graph();
const g = graph.traversal().withRemote(dc);
const vertex = await g.addV(parsedBody.type)
.property(single, 'name', parsedBody.name)
.property(single, 'username', parsedBody.username)
.property('age', parsedBody.age)
.property('purpose', parsedBody.purpose)
.next();
if (vertex.value) {
return callback(null, {
statusCode: 200,
body: vertex.value
});
}
} catch (error) {
console.error(error);
}
};
I keep getting the folowing error from Cloudwatch (I also tried creating a local js file and it gives the same error)
ERROR Error: getaddrinfo ENOTFOUND my-url
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:66:26) {
errno: 'ENOTFOUND',
code: 'ENOTFOUND',
syscall: 'getaddrinfo',
hostname: 'my-url'
}
I also tried to write the endpoint without getting it from process.env and I am still facing the same issue. What am i missing?
Alright for anyone being as confused as I am when trying Neptune for first time. You need to create a database instance aswell, I thought the Serverless Framework would do this to me but now I know.

Making POST call outside of the GCP environment to create workload identity

I need to access GCP resources outside of the GCP environment from AWS using a AWS lambda. So, I found this document [accessing GCP resources from AWS][1] which provides a way to access the GCP resources and asks to create a workload identity pool.
I need to create a Workload identity pool in GCP using a REST API call. The REST API call has to run outside of the GCP environment, that is, in this case from the AWS environment. My GCP's IAM user doesn't have privileges to create a workload identity pool (due to org policy reasons). But, I've a service account which has admin privileges to create a workload identity pool and all the required permissions to access the required resources once the pool is created.
I'm a newbie to GCP and figuring out ways of calling a POST REST API call using my service account credentials. Any help is much appreciated.
Edited
Pasting the sample code I've been trying to make the REST call.
const {google} = require('googleapis');
const util = require('util');
const https = require('https');
const aws4 = require('aws4');
const auth = new google.auth.GoogleAuth({
keyFile: 'serviceAccountCreds.json',
scopes: ['https://www.googleapis.com/auth/cloud-platform'],
});
async function createSignedRequestParams(jsonBodyParams) {
const getAccessToken = await auth.getAccessToken();
console.log(`createSignedRequestParams() - this.credentials:${getAccessToken !== null}`);
// Set up the request params object that we'll sign
const requestParams = {
path: '/v1beta/projects/serviceAccountdev/locations/global/workloadIdentityPools?workloadIdentityPoolId=12345',
method: 'POST',
host: 'iam.googleapis.com',
headers: { 'Content-Type': 'application/json' },
body: jsonBodyParams
};
console.log(`createSignedRequestParams() - (signed) requestParams:${util.inspect(requestParams)}`);
return requestParams;
}
const jsonBodyParams = {
"description": "createWorkloadIdentityPool",
"display-name": "devAccount"
};
async function request(requestParams, jsonBodyParams) {
console.log(`request() requestParams:${util.inspect(requestParams)} jsonBodyParams:${jsonBodyParams}`);
// return new pending promise
return new Promise((resolve, reject) => {
const req = https.request(requestParams);
if (['POST', 'PATCH', 'PUT'].includes(requestParams.method)) {
req.write(jsonBodyParams);
}
req.end();
// Stream handlers for the request
req.on('error', (err) => {
console.log(`request() req.on('error') err:${util.inspect(err)}`);
return reject(err);
});
req.on('response', (res) => {
let dataJson = '';
res.on('data', chunk => {
dataJson += chunk;
});
res.on('end', () => {
const statusCode = res.statusCode;
const statusMessage = res.statusMessage;
const data = JSON.parse(dataJson);
console.log(`request() res.on('end')`, { statusCode, statusMessage, data });
resolve({ statusMessage, statusCode, data });
});
});
});
}
async function postTheRequest(reqParams, jsonBodyParams) {
try {
const response = await request(reqParams, jsonBodyParams);
return response;
} catch (error) {
console.log(error);
}
}
reqParams = createSignedRequestParams(jsonBodyParams);
postTheRequest(reqParams, jsonBodyParams);
output of the above code
[Running] node "c:\Users\av250044\.aws\GCP_Code_examples\registerTheWorkloadIdentifier.js"
request() requestParams:Promise { <pending> } jsonBodyParams:[object Object]
request() req.on('error') err:{ Error: connect ECONNREFUSED 127.0.0.1:443
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1106:14)
errno: 'ECONNREFUSED',
code: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 443 }
{ Error: connect ECONNREFUSED 127.0.0.1:443
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1106:14)
errno: 'ECONNREFUSED',
code: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 443 }
Wondering if I'm passing the PATH and host are correct. Please let me know your thoughts on my code sample.
[1]: https://cloud.google.com/iam/docs/access-resources-aws#iam-workload-pools-add-aws-rest

Unable to verify the first certificate - Nodejs TLS

I'm using the node-module basic-ftp to try to establish a secure connection via TLS/ SSL.
The server uses a wildcard CA-signed certificate as it's hostname. I can't seem to find an answer for the followig error code.
Connected to 1.1.1.1:21
< 220 Welcome to ftp.foo.com
> AUTH TLS
< 234 Using authentication type TLS
{ Error: unable to verify the first certificate
at TLSSocket.onConnectSecure (_tls_wrap.js:1051:34)
at TLSSocket.emit (events.js:189:13)
at TLSSocket._finishInit (_tls_wrap.js:633:8) code: 'UNABLE_TO_VERIFY_LEAF_SIGNATURE'
}
Below you find the sample code:
const ftp = require("basic-ftp");
async establishFtpsConnection() {
const client = new ftp.Client();
client.ftp.verbose = true;
try {
await client.access({
host: "ftp.foo.com",
user: "bar",
password: "1234",
port: 21,
secure: true
});
const list = await client.list();
console.log(list);
} catch (err) {
console.log(err);
}
client.close();
}
NOTE: I'm trying to get it to work for my production environment. So disabling or rejecting unauthorization is NO option for me.
process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = '0';
OR
rejectUnauthorized: false
Try this :
const ftp = require("basic-ftp");
async establishFtpsConnection() {
const client = new ftp.Client();
client.ftp.verbose = true;
const tlsOptions = {
cert: fs.readFileSync('fullchain.pem', 'ascii')
// a PEM containing the SERVER and ALL INTERMEDIATES
}
try {
await client.access({
host: "ftp.foo.com",
user: "bar",
password: "1234",
port: 21,
secure: true,
secureOptions:tlsOptions
});
const list = await client.list();
console.log(list);
} catch (err) {
console.log(err);
}
client.close();
}
If you are still getting an error then try to inject root SSL certificates
var sslRootCAs = require('ssl-root-cas/latest')
sslRootCAs.inject()

Error method sendAll() in nodejs using firebase-admin

I use firebase-admin for nodejs(version 7.3.0) for sending push
notifications. For 40k distinct messages sending with method sendAll often server received this error:
"Credential implementation provided to initializeApp() via the "credential"
property failed to fetch a valid Google OAuth2 access token with the
following error: "Error fetching access token: Error while making request:
socket hang up. Error code: ECONNRESET".
Sometimes it works well but not all the time.
var admin = require('firebase-admin');
serviceAccount = require('/path_json_adminsdk/yyyyyyyyyy.json');
var defaultApp = admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: 'https://api-project-yyyyyy'
});
var k = 42000;
var contorMessages = 0;
var messages = [];
for(var i=0;i <em><</em> k; i++){
//.......
contorMessages = contorMessages + 1;
var tmp = {
alert: body.alert,
payload: body.payload
};
//form the array to be sent
messages.push({
data: {"body": JSON.stringify(tmp)},
token: body.token
});
if(contorMessages == 100){
SEDispatcher.emit('sendMessageFirebaseMulticast',messages);
contorMessages = 0;
messages = [];
}
}
SEDispatcher.on('sendMessageFirebaseMulticast', function(messages){
var dryRun = true;
admin.messaging().sendAll(messages, dryRun)
.then(function(response) {
//console.log("response:",response);
//responses = response.responses;
//.......
})
.catch((error) => {
console.log(' +++ Error sending message:', error);
});
});
the error that occurs sometimes:
+++ Error sending message: { Error: Credential implementation provided to initializeApp() via the "credential" property failed to fetch a
valid Google OAuth2 access token with the following error: "Error
fetching access token: Error while making request: socket hang up.
Error code: ECONNRESET".
at FirebaseAppError.Error (native)
at FirebaseAppError.FirebaseError [as constructor] (/opt/node/test/node_modules/firebase-admin/lib/utils/error.js:42:28)
at FirebaseAppError.PrefixedFirebaseError [as constructor] (/opt/node/test/node_modules/firebase-admin/lib/utils/error.js:88:28)
at new FirebaseAppError (/opt/node/test/node_modules/firebase-admin/lib/utils/error.js:122:28)
at /opt/node/test/node_modules/firebase-admin/lib/firebase-app.js:121:23
at process._tickCallback (internal/process/next_tick.js:103:7) errorInfo: { code: 'app/invalid-credential',
message: 'Credential implementation provided to initializeApp() via the "credential" property failed to fetch a valid Google OAuth2
access token with the following error: "Error fetching access token:
Error while making request: socket hang up. Error code: ECONNRESET".'
}, codePrefix: 'app' }
const messaging = getMessaging(defaultApp);
Need to be load
let serviceAccount = require('./google.json');
function messaging() {
const defaultApp = initializeApp({
credential: admin.credential.cert(serviceAccount)
});
const messaging = getMessaging(defaultApp);
const topic = 'highScores';
const message = [
{
data: {
score: '850',
time: '2:45'
},
topic: topic
}
];
messaging
.sendAll(message, true)
.then(function (response) {
console.log('response:', response);
})
.catch((error) => {
console.log(' +++ Error sending message:', error);
});
}
Assuming that the JSON is the file that contains your private key that is generated when registering the project

Unable to connect to Realm Object Server using NodeJs

I've installed Realm Object Server using the docker container method on a VM on the google cloud platform. The container is running and I am able to connect in a browser and see the ROS page. I am able to connect to it using Realm Studio and add a user.
I have a nodeJS app running locally on a Mac and I'm trying to use that to sign in and write to realm on the server. When I run the app I get an error and the user returned is an empty object. Not sure what I'm doing wrong.
I'm new to NodeJS.
Code:
var theRealm;
const serverUrl = "http://xx.xx.xx.xx:9080";
const username = "xxxx";
const password = "xxxx";
var token = "long-token-for-enterprise-trial";
Realm.Sync.setFeatureToken(token);
console.log("Will log in user");
Realm.Sync.User.login(serverUrl, username, password)
.then(user => {
``
// user is logged in
console.log("user is logged in " + util.inspect(user));
// do stuff ...
console.log("Will create config");
const config = {
schema:[
schema.interventionSchema,
schema.reportSchema
],
sync: {
user: user,
url: serverUrl
}
};
console.log("Will open realm with config: " + config);
const realm = Realm.open(config)
.then(realm => {
// use the realm instance here
console.log("Realm is active " + realm);
console.log("Will create Realm");
theRealm = new Realm({
path:'model/realm_db/theRealm.realm',
schema:[
schema.interventionSchema,
schema.reportSchema
]
});
console.log("Did create Realm: " + theRealm);
})
.catch(error => {
// Handle the error here if something went wrong
console.log("Error when opening Realm: " + error);
});
})
.catch(error => {
// an auth error has occurred
console.log("Error when logging in user: " + error);
});
Output:
Will log in user
Server is running...
user is logged in {}
Will create config
Will open realm with config: [object Object]
TypeError: Cannot read property 'token_data' of undefined
at performFetch.then.then (/pathToProject/node_modules/realm/lib/user-methods.js:203:49)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:188:7)
TypeError: Cannot read property 'token_data' of undefined
at performFetch.then.then (/pathToProject/node_modules/realm/lib/user-methods.js:203:49)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:188:7)
Error # user-methods.js:203:49
const tokenData = json.access_token.token_data;
json is:
{ user_token:
{ token: 'xxxxxxxx',
token_data:
{ app_id: 'io.realm.Auth',
identity: 'xxxxxxx',
salt: 'xxxxxxxx',
expires: 1522930743,
is_admin: false } } };
So json.access_token.token_data is undefined but json. user_token.token_data would not be.
I would suggest you to try the ROS connection with realm studio in that u can check logs as well which will help you to fix the error. If your still not able to fix then you can contact Realm support team even they helped me to fix the issue of ROS connection in Xamarin Forms using Docker.

Resources