Unable to call watson language translator using proxy - nginx

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.

Related

NTLM requests in K6 and .NEТ Core

I wrote load testing of my API with NTLM auth (here I additionally check if NTLM authorized user is presend in Database). During resquest:
var url = 'https://login:*****#localhost:xxxx/api/authorization/logon';
var payload = { };
var params = {
headers: {
'Content-Type': 'application/json'
},
};
let response = http.post(url, params, {auth: "ntlm"});
check(response, {
'status is 200': (r) => r.status === 200
});
}
i have an error:
error="Post "https://user:*****#localhost:xxx/api/authorization/logon": stream error: stream ID 3; HTTP_1_1_REQUIRED".
Why? Kestrel serve HTTP/1.1
This is an issue in the way Go standard library's HTTP client operates, that is described here in detail, in which for HTTPS endpoints, connection is forcibly upgraded to HTTP/2.0, which is not supported by the NTLM protocol.
I'm not sure, but maybe you can disable this connection upgrade in Kestrel.
you can set in your global system environment to enable HTTP1.1

Verifying reCAPTCHA v3 in Firebase Function causes CORS Issue

I have the following codes that verify Google reCAPTCHA v3 in my Firebase Function that caused the CORS issue:
const functions = require('firebase-functions');
const nodemailer = require("nodemailer");
const express = require("express");
const cors = require("cors");
const request = require('request');
const serverApi = express();
api.use(cors({ origin: true }));
function verifyCaptcha(token, returnData) {
// Put your secret key here.
var secretKey = functions.config().recaptcha.secretkey;
var verificationUrl = "https://www.google.com/recaptcha/api/siteverify?secret=" + secretKey + "&response=" + token;
// Note here: External network call to google.com
request(verificationUrl, function (error, response, body) {
body = JSON.parse(body);
// Success will be true or false depending upon captcha validation.
if (!body.success) {
body['status'] = false;
body['errSource'] = "recaptcha";
body['message'] = "Failed to pass captcha verification.";
} else {
body['status'] = true;
body['message'] = "Successfully passed captcha verification!";
};
console.log(`Google returns: ${JSON.stringify(body)}`);
returnData(body);
});
};
api.post("/api/service-name", (req, res) => {
if (!req.body['g-recaptcha-response']) {
return res.send({ "status": false, "errSource": "recaptcha", "message": "Client-side reCAPTCHA token not found." });
};
const recaptchaToken = req.body['g-recaptcha-response'];
verifyCaptcha(recaptchaToken, function (result) {
if (result.status == false) {
return res.send(result);
};
// My business logics here.
});
});
exports.api = functions.https.onRequest(api);
I noticed that after removing the reCAPTCHA v3 verification request in within my Firebase Function, no more CORS issue for my localhost to call "/api/service-name" using $.ajax(). This is because the following Firebase Function log reminded me of the "External network is not accessible":
Billing account not configured. External network is not accessible and quotas are severely limited.
Configure billing account to remove these restrictions
My question is: Is there a way to get my server-side reCAPTCHA verification to work without causing this CORS issue, which could be prevented by "Billing account not configured"? Thanks!
UPDATE:
After catching the request() error that does the verification, I get the following error:
{errno: "EAI_AGAIN", code: "EAI_AGAIN", syscall: "getaddrinfo", hostname: "www.google.com", host: "www.google.com", …}
Also, after handling this error, no more CORS issue, but reCAPTCHA still cannot be verified. Any idea what causes this? Thanks again!
It's now confirmed that the above issue has been resolved after Enable Billing at the Google Cloud Console. It is NOT actually the CORS issue between the localhost and Firebase Functions/Hosting (although the Chrome browser returned as CORS related error message), it's actually the HTTP Request from the Firebase Function to the Google reCAPTCHA api during token verification process. Due to billing account not linked to the Firebase Project where the function sits in, any requests from any Firebase Functions to any External Network Resources, including Google reCAPTCHA, will be rejected with the following errors:
HTTP Request Error:
{errno: "EAI_AGAIN", code: "EAI_AGAIN", syscall: "getaddrinfo", hostname: "www.google.com", host: "www.google.com", …}
After enabling billing at GCP and linking the billing account to the specific Firebase Project, the request to Google reCAPTCHA verification will be successful (if the token is valid) without the above error. However, your FREE Spark Tier Firebase account will be AUTOMATICALLY UPGRADED to Blaze Plan -- Pay as you go.

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 client error: Custom token corresponds to a different audience

I'm using the Firebase Python AdminSDK to generate a custom token which a Javascript client uses to sign in to Firebase. When the JS client tries to authenticate with the custom token it gets the error "Custom token corresponds to a different audience".
The code given with the error: 'auth/custom-token-mismatch'.
Many Google'd answers regarding the "audience" mismatch reference Analytics. But I'm doing a Web project, not iOS or Android, so I can't use Analytics to manage audiences.
The SO answers I've read are listed at the end, below.
I captured the custom token and plugged it in to https://jwt.io/ and both the values and the instanciation/expiration times (an hour apart) look good:
Decoded custom token on jwt.io:
{
"claims": {},
"uid": "<myuniqueID",
"sub": "firebase-adminsdk-1knpr#firebase-<myproject>.iam.gserviceaccount.com",
"iss": "firebase-adminsdk-1knpr#firebase-<myproject>.iam.gserviceaccount.com",
"iat": 1540153710,
"aud": "https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",
"exp": 1540157310
}
Python server:
def getFirebaseInstance(): # For Firebase Python SDK
try:
currentDir_path = os.path.dirname(os.path.realpath(__file__))
cred = credentials.Certificate(currentDir_path + '/includeFirebaseServiceAccounts/firebase-<myprojectname>-firebase-adminsdk-1knpr-e1244dd261.json')
firebaseAdmin = firebase_admin.initialize_app(cred, { 'databaseURL': 'https://<myprojectname>.firebaseio.com', 'databaseAuthVariableOverride': {'uid':'<myuniqueServerID>'}})
if firebaseAdmin:
return(firebaseAdmin)
except:
raise
def firebaseClientToken(request):
try:
uid = "<myuniqueClientID>" # case sensitive
additional_claims = { }
token = auth.create_custom_token(uid,additional_claims)
return HttpResponse(token)
except Exception as err:
return HttpResponse("System error:" + str(err), status=406)
Javascript client:
(
function authClient2Firebase() {
$.ajax({
url: "firebaseClientToken/",
method: "POST",
success: function(response) { step2(response); },
error: function(xhr) { alert("There was an error loading a security check. Have you lost your internet connection? Detail:" + xhr.responseText); }
});
function step2(customToken) {
try {
firebase.auth().signInWithCustomToken(customToken).catch(function(error) {
var errorCode = error.code;
var errorMessage = error.message;
alert("There was an error with the secure login. \n\nDetail: " + errorMessage + '\nCode: ' + errorCode);
});
}
catch(err) {
alert(err);
}
console.log("authClient2Firebase.js: Firebase login succeeded!");
}
}
)();
My project under the Console "Settings" page does have a Web API key, but I don't see anywhere that it's used.
There's only one user, me, under the Console's "Settings"->"Users and Permissions" page.
There's only one service account listed on the Console "Settings"->"Service Accounts" page. I tried deleting all secrets on that page, generating a new one, then generating and installing a new blue-button "secret" (bad name, actually it generates a whole json credential object).
These are the domains listed in Console "Authentication" -> "Sign-in Method":
localhost Default
<myproject>.firebaseapp.com Default
127.0.0.1 Custom
auth.firebase.com Custom
The actual domain I'm using is localhost:8000, which can't be entered here.
SO answers consulted unsuccessfully:
The custom token corresponds to a different audience
(I'm not using a key, except what's stored in the ServiceAccount
credentials.)
Firebase token error, "The custom token corresponds to a different audience."
Firebase custom auth issue token different audienceenter
link description here (Close, but I'm not using a Node server and
not sure what he means by server "must belong to the same project"
since the Python server isn't registered in any way except through the
ServiceAccount credentials which I downloaded.)
Embarrassing but true, it turned out to be a simple oversight. When the JS client initialized itself as a Firebase app, before authenticating, it was using old credentials from a test environment.
// Initialize Firebase
var config = {
apiKey: "<WebAPI from Firebase console, 'Project Settings'>",
authDomain: "<myproject>.firebaseapp.com",
databaseURL: "https://<myproject>.firebaseio.com",
projectId: "<myproject>",
storageBucket: "<myproject>.appspot.com",
messagingSenderId: "<id from Console Project Settings>" // optional
};
firebase.initializeApp(config);

SingalR ASP.NET Cross Domain Connection Issue

I am trying to implement an ASP.NET SignalR app as mentioned here.
I have implemented the client as mentioned here. For the client I am using code without the generated proxy.
Client and server successfully connect when both are on the same domain but unable to communicate when hosted cross domain. Although the code mentioned for cross domain in the above articles is already implemented. Since my client and server are hosted in Azure, is there a setting in Azure that needs to be enabled for cross domain communication or there is something else that I am missing?
Here is the error i am getting:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin is therefore not allowed access. The response had HTTP status code 500.
My startup class is:
public void Configuration(IAppBuilder app)
{
//app.UseCors(CorsOptions.AllowAll);
// Any connection or hub wire up and configuration should go here
//app.MapSignalR();
// Branch the pipeline here for requests that start with "/signalr"
app.Map("/signalr", map =>
{
// Setup the CORS middleware to run before SignalR.
// By default this will allow all origins. You can
// configure the set of origins and/or http verbs by
// providing a cors options with a different policy.
map.UseCors(CorsOptions.AllowAll);
var hubConfiguration = new HubConfiguration
{
// You can enable JSONP by uncommenting line below.
// JSONP requests are insecure but some older browsers (and some
// versions of IE) require JSONP to work cross domain
// EnableJSONP = true
};
// Run the SignalR pipeline. We're not using MapSignalR
// since this branch already runs under the "/signalr"
// path.
map.RunSignalR(hubConfiguration);
});
}
And the client code is:`
$(function (){
var ChatServerUrl ="http://chatserverurl.net/home/";
var ChatUrl = ChatServerUrl + "signalr";
var connection = $.hubConnection(ChatUrl, { useDefaultPath: false });
connection.logging = true;
var chatHubProxy = connection.createHubProxy('chatHub');
chatHubProxy.on('addNewMessageToPage', function (name, message) {
console.log("AddNewMessageToPage Function!");
// Add the message to the page.
$('#discussion').append('<li><strong>' + htmlEncode(name)
+ '</strong>: ' + htmlEncode(message) + '</li>');
});
// Get the user name and store it to prepend to messages.
$('#displayname').val(prompt('Enter your name:', ''));
// Set initial focus to message input box.
$('#message').focus();
// Start the connection.
//connection.start({ withCredentials : false }).done(function () {
connection.start({ withCredentials: true }).done(function () {
$('#sendmessage').click(function () {
// Call the Send method on the hub.
chatHubProxy.invoke('Send', $('#displayname').val(), $('#message').val());
// Clear text box and reset focus for next comment.
$('#message').val('').focus();
});
console.log("SignalR Connected!");
});
});`
Please try this according to what the below links suggest
https://learn.microsoft.com/en-us/aspnet/signalr/overview/guide-to-the-api/hubs-api-guide-javascript-client

Resources