GRPC with HTTP transcoding and CORS - error case issue - http

Transcoding is working for the non-error use case.
I had to configure nginx differently to enable CORS (which is not clear in the docs IMO).
I use grpc java and handle an error like this for the simple hello message:
#Override
public void sayHello(UserOuterClass.HelloRequest request, StreamObserver<UserOuterClass.HelloReply> responseObserver) {
log.info("there is a hello request");
if(request.getName().equals("coucou")){
log.info("coucou is forbidden");
responseObserver.onError(Status.NOT_FOUND.asException());
return;
}
UserOuterClass.HelloReply.Builder replyBuilder = UserOuterClass.HelloReply.newBuilder();
replyBuilder.setMessage("coucou " + request.getName());
responseObserver.onNext(replyBuilder.build());
responseObserver.onCompleted();
log.info("there has been a response");
}
Now when a request is sent from chrome there is a preflight call which seems ok. But the GET itself corresponding to sayHello function above fails with a CORS issue:
Failed to load http://xxxxxx:8080/v1/hello?name=coucou: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 404.
If the response is ok, the cors headers are present. If it's an error like here, then the cors header are not there.
Moreover here is the response returned by endpoints:
{
"code": 5,
"message": "",
"details": [
{
"#type": "type.googleapis.com/google.rpc.DebugInfo",
"stackEntries": [],
"detail": "internal"
}
]
}

Related

Unable to make API call in NextJS app running on port different that port 3000

I am currently a CORS issue in my NextJs App. When I run the app on let's say on localhost:3030, and I make an API call to http://some-api.com, I get the following error:
Access to XMLHttpRequest at 'http://some-api.com' from origin 'http://localhost:3030' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header has a value 'http://localhost:3000' that is not equal to the supplied origin.
I added the following lines to the next.config.js.
process.env.NEXT_PUBLIC_SOME_HOST=http://some-api.com
async rewrites() {
return [
{
source: '/api/:path*',
destination: process.env.NEXT_PUBLIC_SOME_HOST + '/:path*'
}
]
},
//avoiding CORS error, more here: https://vercel.com/support/articles/how-to-enable-cors
async headers() {
return [
{
// matching all API routes
source: "/api/:path*",
headers: [
{ key: "Access-Control-Allow-Credentials", value: "true" },
{ key: "Access-Control-Allow-Origin", value: process.env.NEXT_PUBLIC_SOME_HOST},
{ key: "Access-Control-Allow-Methods", value: "GET,OPTIONS,PATCH,DELETE,POST,PUT" },
{ key: "Access-Control-Allow-Headers", value: "X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version" },
]
}
]
},
But it still does not work.
I also attached of the response header on the OPTIONS call.
I can see that the access-control-allow-origin is set to http:localhost:3000 I think if I override that value to localhost:3030 it would work but I am not sure how to do that.
I am pretty new to NextJs, so some help would be greatly appreciated.
Updating the CorsFilter on the Back end API to allow response to http://localhost:3030 solved the problem.
My back end API is written in Spring Boot.
So I added the following:
httpServletResponse.setHeader("Access-Control-Allow-Origin", "http://localhost:3030");
Note: It also possible to allow all with "*"

How to use token base auth in jupyterhub?

I am trying to use jupyterhub using token-based which is in Iframe.
I had tried using postman by sending token as header it worked.
But in browser
$.ajax({
type : "GET",
url : "http://jupiter.****.com/hub/login",
beforeSend: function(xhr){xhr.setRequestHeader('Authorization', 'token *****');
},
success : function(result) {
},
error : function(result) {
}
});
It gives me a Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at ***. (Reason: CORS request did not succeed)
I had configured jupyterhub_config.py
c.JupyterHub.tornado_settings = {'headers': {'Content-Security-Policy': "frame-ancestors * 'self' " ,'Access-Control-Allow-Origin': '*','Access-Control-Allow-Methods':'*','Access-Control-Allow-Headers':'*','Access-Control-Allow-Credentials':'true'}}
c.Spawner.args = [f'--NotebookApp.allow_origin=*']
Any pointers/advice on how to implement this would be greatly appreciated!

Firestore HTTP Insomnia query : Stream error in the HTTP/2 framing layer

I'm trying to query my Firestore database using an HTTP query via the Insomnia API:
https://firestore.googleapis.com/v1/projects/typebot/databases/(default)/documents/users
with this body:
{
"structuredQuery": {
"from": [
{
"collectionId": "users"
}
],
"where": {
"fieldFilter": {
"field": {
"fieldPath": "email"
},
"op": "EQUAL",
"value": {
"stringValue": "email#test.com"
}
}
}
}
}
And I get the following error:
HTTP query: Stream error in the HTTP/2 framing layer
Any idea what's wrong?
May try to change "GET" to "POST"
I had a similar problem performing a GET request:
GET https://us-central1-my-project-id.cloudfunctions.net/getUsers HTTP/1.1
content-type: application/json
{
"minAge": "18"
}
against an endpoint defined by this Firestore HTTP Cloud Function:
exports.getUsers = functions.https.onRequest(async (req, res) => {
// find matching users by age limit.
const ageLimit = req.body.age;
...
});
Turns out, based on this other SO post, that a request body with GET does not have any meaning in the sense that the HTTP spec recommends that the "message-body SHOULD be ignored when handling the request" (presumably, by the server, and that the Firestore server implements this behavior). Oddly, I didn't catch this issue running the exact same function locally with the Functions emulator, so it is likely the local server ignores this recommendation.
To fix the issue, I changed my function to parse the query params instead of a request body:
exports.getUsers = functions.https.onRequest(async (req, res) => {
// find matching users by age limit.
const ageLimit = req.query.age; // extract the age as a query param
...
});
and the request:
GET https://us-central1-my-project-id.cloudfunctions.net/getUsers?age=18

Cannot see error message in http response in Kotlin Fuel

I am sending an HTTP PUT request to my Elasticsearch server using Fuel library on Kotlin. However, I cannot see an error body if the server returns 404 or 400. I am expecting to get an error message similar to the following:
{
"error": {
"root_cause": [
{
"type": "invalid_snapshot_name_exception",
"reason": "[snap1:kopya3]Invalid snapshot name [kopya3], snapshot with the same name already exists"
}
],
"type": "invalid_snapshot_name_exception",
"reason": "[snap1:kopya3]Invalid snapshot name [kopya3], snapshot with the same name already exists"
},
"status": 400
}
Here's my code:
val (request, response, result) = fullUrl
.httpPut()
.body(payload)
.responseString()
val (bytes, error) = result
print(error)
Instead what I see is:
HTTP Exception 400 Bad Request
com.github.kittinunf.fuel.core.FuelError$Companion.wrap(FuelError.kt:84)
com.github.kittinunf.fuel.core.DeserializableKt.response(Deserializable.kt:168)
com.github.kittinunf.fuel.core.requests.DefaultRequest.responseString(DefaultRequest.kt:475)
com.a.b.c.d.model.Cluster.createSnapshot(Cluster.kt:67)
com.a.b.c.d.model.Cluster.createSnapshot$default(Cluster.kt:57)
com.a.b.c.d.model.ClusterKt.main(Cluster.kt:85)
Caused by: HTTP Exception 400 Bad Request
com.github.kittinunf.fuel.core.FuelError$Companion.wrap(FuelError.kt:86)
Caused by: com.github.kittinunf.fuel.core.HttpException: HTTP Exception 400 Bad Request
com.github.kittinunf.fuel.core.requests.RequestTask.prepareResponse(RequestTask.kt:35)
com.github.kittinunf.fuel.core.requests.RequestTask.call(RequestTask.kt:47)
com.github.kittinunf.fuel.core.requests.RequestTask.call(RequestTask.kt:14)
com.github.kittinunf.fuel.core.DeserializableKt.response(Deserializable.kt:166)
com.github.kittinunf.fuel.core.requests.DefaultRequest.responseString(DefaultRequest.kt:475)
com.a.b.c.d.model.Cluster.createSnapshot(Cluster.kt:67)
com.a.b.c.d.model.Cluster.createSnapshot$default(Cluster.kt:57)
com.a.b.c.d.model.ClusterKt.main(Cluster.kt:85)
How can I see the actual error message? Thanks in advance.
I solved my problem by looking at response.data which is a bytes array. Converting it to string by String(response.data) I could see the error message.
It's really quite annoying that the default exception doesn't just print this.
I struggled with the generics on this one to pull the handler into its own function, so I thought I share my complete code here.
fun <T> genericErrorHandler(response: Response, result: Result.Failure<Exception>): T {
println("Request to url ${response.url} failed, server returned:")
println(String(response.data))
throw result.getException()
}
private fun someRequest(url: String, jsonBody: String): SomeDataFormatYouExpectOnSuccess {
val (_, response, result) = url.httpPost().header("Content-Type", "application/json; utf-8")
.header("Authorization", "") // adding some headers
.jsonBody(jsonBody)
.responseString()
return when (result) {
is Result.Failure -> genericErrorHandler(response, result)
is Result.Success -> {
val data = result.get()
gson.fromJson(data, SomeDataFormatYouExpectOnSuccess::class.java)
}
}
}

Parse.com push api - randomly returns 404

I have a problem with parse api. I'm sending this data:
{
"where": {
"deviceType": "android"
},
"data": {
"action": "somestring",
"aps": {
"alert": "some title",
"id": 4353453,
"s": "some_short_string"
}
}
}
to https://api.parse.com/1/push using POST method with headers:
Content-Type: "application/json",
X-Parse-Application-Id: "myid",
X-Parse-REST-API-Key: "mykey",
User-Agent: "PHPWebapiClient"
Api returns mostly status 200, but sometimes it returns 404. Of course in this case notifications wont work, and even don't appear in parse admin. It seems totally random, i can't determine the cause. Interestingly api always return this header:
http_code: "HTTP/1.0 200 Connection established"
no matter what response code is returned.
I tried resending request, but this didn't help.
Is there anyone experiencing similar problems? Please help me sort this out.

Resources