Setup Quart server with HTTP/2 - google-chrome

I am trying to setup a Quart server to play with HTTP/2. I have been trying to go through the minimal documentation at:
https://gitlab.com/pgjones/quart
Where I have:
$ cat app.py
from quart import Quart, render_template, websocket
app = Quart(__name__)
#app.route("/")
async def hello():
return await render_template("index.html")
#app.route("/api")
async def json():
return {"hello": "world"}
#app.websocket("/ws")
async def ws():
while True:
await websocket.send("hello")
await websocket.send_json({"hello": "world"})
if __name__ == "__main__":
app.run(host="0.0.0.0", port=5001)
Some basic check:
$ curl -I --http2 http://acme.corp:5001
HTTP/1.1 101
date: Tue, 02 Mar 2021 10:05:12 GMT
server: hypercorn-h11
connection: upgrade
upgrade: h2c
HTTP/2 200
content-type: text/html; charset=utf-8
content-length: 0
date: Tue, 02 Mar 2021 10:05:12 GMT
server: hypercorn-h2
Looking at the output
$ python3 app.py
* Serving Quart app 'app'
* Environment: production
* Please use an ASGI server (e.g. Hypercorn) directly in production
* Debug mode: False
* Running on http://0.0.0.0:5001 (CTRL + C to quit)
[2021-03-02 11:01:49,083] Running on http://0.0.0.0:5001 (CTRL + C to quit)
[2021-03-02 11:01:53,011] 10.221.0.114:53637 GET / 1.1 200 0 5817
[2021-03-02 11:01:53,255] 10.221.0.114:53637 GET /favicon.ico 1.1 404 103 1348
Here is what I see, when I load the index.html page from chrome:
What am I missing to get http/2 from chrome ?

Locally you are upgrading an insecure HTTP 1.1 request to an insecure HTTP 2 request. This works with Quart and curl, but browsers including chrome do not support insecure (unencrypted) HTTP/2. For it to work in chrome I create a self signed certificate, passing the certfile and keyfile options to the run and accept the warning chrome offers when visiting the site. An example exists here.

Related

CouchDB _session not returning cookie

Environment:
CouchDB 2.2.0 running on VirtualBox, running up-to-date Debian image. Network type is bridged, all ports are open, no https.
Vue3.js app (not using any Vue functionality to access the DB)
Remote access JS package:
axios
fetch
Browser: Chrome latest
Relevant CouchDB local.ini settings
[couch_peruser]
enable = false
delete_dbs = false
[chttpd]
port = 5984
require_valid_user = false
proxy_use_secret = false
bind_address = 0.0.0.0
authentication_handlers = {chttpd_auth, cookie_authentication_handler}, {chttpd_auth, default_authentication_handler}
[httpd]
bind_address = 127.0.0.1
enable_cors = true
(default authentication handlers set in default.ini)
authentication_handlers = {couch_httpd_auth, cookie_authentication_handler}, {couch_httpd_auth, default_authentication_handler}
[couch_httpd_auth]
secret = (hash num)
require_valid_user = false
allow_persistent_cookies = true
[cors]
origins = *
headers = accept, authorization, content-type, X-Auth-CouchDB-UserName, origin, referer
credentials = true
methods = GET, PUT, POST, HEAD, DELETE
What Happens
If I do the query via curl, I get a cookie in the response.
Here's the curl call:
curl -v http://couchman.lcldev:5984/_session \
-H "Content-Type:application/json" \
-H "X-Auth-CouchDB-UserName:<uname>" \
-d '{"name":"<uname>","password":"<passwd>"}'
And here's the response:
< HTTP/1.1 200 OK
< Cache-Control: must-revalidate
< Content-Length: 47
< Content-Type: application/json
< Date: Wed, 10 Oct 2018 21:16:10 GMT
< Server: CouchDB/2.2.0 (Erlang OTP/19)
< Set-Cookie: (cookie info)
<
{"ok":true,"name":"<name>","roles":["<roles>"]}
Yay. I get a cookie.
But if I call it from within my app (with either fetch or axios), I only get these headers:
Response headers:
cache-control,must-revalidate
content-type,application/json
server,CouchDB/2.2.0 (Erlang OTP/19)
No Set-Cookie header.
So, what's up? What am I missing?
Answered in first comment - see thread for more info.

Fiware error: Access-Control-Allow-Origin

I'm making a call to the contextBroker and it gives me this error.
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 405.
From postman or from freeboard I do not get any of this.
getContextBroker(){
console.log("Consumimos el servicio getContextBroker");
let headers = new Headers ({'Accept': 'application/json', 'Fiware-Service': 'x', 'Fiware-ServicePath': '/x', 'Access-Control-Allow-Origin': '*'});
let options = new RequestOptions ({headers : headers});
return this._http.get(this.urlcontextBrokers, {headers : headers}).map(res => res.json());
}
}
how can I solve that?
I've tried adding: 'Access-Control-Allow-Origin': '*'
But it still does not work
EDIT:
ps ax | grep contextBroker:
862 pts/4 S+ 0:00 grep contextBroker
3792 ? Ssl 27:35 /usr/bin/contextBroker -port 1026 -logDir /var/log/contextBroker -pidpath /var/run/contextBroker/contextBroker.pid -dbhost localhost -db orion -multiservice -logAppend
version:
{
"orion": {
"version": "1.7.0",
"uptime": "12 d, 18 h, 24 m, 20 s",
"git_hash": "e544780eb64a4a2557c1f51dde070b8d82b86c49",
"compile_time": "Wed Feb 8 13:30:24 CET 2017",
"compiled_by": "fermin",
"compiled_in": "centollo"
}
}
EDIT02
Hello, as I said, I do not want to use the cors, I have eliminated that from the header in such a way:
   getContextBroker () {
     console.log ("We consume the getContextBroker service");
     let headers = new Headers ({'Accept': 'application / json', 'Fiware-Service': 'IoFAlmeria', 'Fiware-ServicePath': '/ ARMpalmerillas'});
     let options = new RequestOptions ({headers: headers});
     return this._http.get (this.urlcontextBrokers, {headers: headers}). map (res => res.json ());
   }
}
and I keep giving the same error:
OPTIONS http: // XXX: 1026 / v2 / entities / 405 (Method Not Allowed)
Failed to load http: // XXX: 1026 / v2 / entities /: Response to preflight request does not pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http: // localhost: 4200' is therefore not allowed access. The response had HTTP status code 405.
it has to be the problem of the fiware API since I have designed one with nodejs and I have no problem changing the URL
Update:
Limpiando repositorios:base epel extras fiware mongodb-org-3.2
: mysql-connectors-community mysql-tools-community
: mysql57-community nodesource updates
Limpiando todo
Cleaning up list of fastest mirrors
[root#UAL-IoF2020 ~]# yum install contextBroker
Complementos cargados:fastestmirror, refresh-packagekit, security
Configurando el proceso de instalación
Determining fastest mirrors
epel/metalink | 25 kB 00:00
* base: ftp.uma.es
* epel: ftp.uma.es
* extras: ftp.uma.es
* updates: ftp.uma.es
base | 3.7 kB 00:00
base/primary_db | 4.7 MB 00:00
epel | 4.7 kB 00:00
epel/primary_db | 6.0 MB 00:00
extras | 3.4 kB 00:00
extras/primary_db | 29 kB 00:00
fiware | 951 B 00:00
fiware/primary | 45 kB 00:00
mongodb-org-3.2 | 2.5 kB 00:00
mongodb-org-3.2/primary_db | 78 kB 00:00
mysql-connectors-community | 2.5 kB 00:00
mysql-connectors-community/primary_db | 18 kB 00:00
mysql-tools-community | 2.5 kB 00:00
mysql-tools-community/primary_db | 38 kB 00:00
mysql57-community | 2.5 kB 00:00
mysql57-community/primary_db | 139 kB 00:00
nodesource | 2.5 kB 00:00
nodesource/primary_db | 51 kB 00:00
updates | 3.4 kB 00:00
updates/primary_db | 6.4 MB 00:00
El paquete contextBroker-1.7.0-1.x86_64 ya se encuentra instalado con su versión más reciente
Nada para hacer
CORS requests are only supported by Orion Context Broker version 1.10 and above.
As #JoseManuelCantera has pointed out, you do not need to add any CORS specific headers to your request, those are handled by your client (browser, Postman etc.)
You need to:
Upgrade your version to 1.10
Start Orion in CORS mode
You can start Orion in CORS mode for any origin (Orion will accept CORS requests from any origin) as below:
contextBroker -corsOrigin __ALL
Please take a look at the CORS documentation for Orion for more information.
UPDATE
Please allow me to shortly explain CORS pre-flight logic. If your request is not a simple request, your browser will do a pre-flight request prior to yours with the OPTIONS method. If Orion is not started in CORS mode, you will always get method not allowed as a response to your non-simple requests.
So what is the problem, why are you getting different results with different clients? Postman (curl etc.) does exactly what you want it to do and sends the requests as you have configured. It does not check if the request you are sending should be pre-flighted or not.
On the other hand, your browser does check your request and do a pre-flight if necessary. You have no control over this other than modifying your request.
The Javascript framework you are working with is probably adding a header to the request rendering it a "non-simple" request. For example: X-Requested-With. Please see this question.
My suggestion is to take a look at the details of the request your browser sends (headers, methods etc.) and see what makes it a non-simple request. Then do the necessary changes on your js code to make sure your request falls within the scope of simple requests.
Having said that, you will need to upgrade your Orion version eventually since for example, a DELETE request is never going to be treated as a simple request when sent over a browser.
I think you need to upgrade to version 1.10 so that you can use CORS.
You do not need to add any header ;) and actually the Access-Control-Allow-Origing header is sent in the server response not by the client request

Error when accessing rest service from WebExtension using XMLHttpRequest

I am trying to access a rest service that I am hosting on an amazon AWS server from a firefox WebExtension.
I have registered a background script in the manifest.json which then tries to access the service.
"background": {
"scripts": ["OwnerLangBackground.js"]
},
"permissions": [
"*://ec2-35-158-91-62.eu-central-1.compute.amazonaws.com:9000/*"
]
However, the XMLHttpRequest just returns an error but I don't see what goes wrong. While researching this issue, I stumbled across the following page:
https://mathiasbynens.be/notes/xhr-responsetype-json
Replacing my own code with a (slightly modifed) copy of the code from the above link I now have:
// OwnerLangBackground.js
console.log("OwnerLangBackground.js loaded");
var getJSON = function(url, successHandler, errorHandler) {
var xhr = new XMLHttpRequest();
xhr.open('get', url, true);
xhr.onreadystatechange = function() {
var status;
var data;
// https://xhr.spec.whatwg.org/#dom-xmlhttprequest-readystate
if (xhr.readyState == 4) { // `DONE`
status = xhr.status;
if (status == 200) {
data = JSON.parse(xhr.responseText);
successHandler && successHandler(data);
} else {
errorHandler && errorHandler(status, xhr.responseText);
}
}
};
xhr.send();
};
/* BLOCK 1: removing the comments for this block works
getJSON('https://mathiasbynens.be/demo/ip', function(data) {
console.log('Your public IP address is: ' + data.ip);
console.log('Your response is: ', data);
}, function(status) {
console.warn('Something went wrong.', status);
});
*/
/* BLOCK 2: removing the comments for this block, does not work
getJSON('http://ec2-35-158-91-62.eu-central-1.compute.amazonaws.com:9000/get-languages', function(data) {
console.log('Your response is: ', data);
}, function(status) {
console.warn('Something went wrong.', status);
});
*/
Strangely enough, activating BLOCK 1 works as expected (ip address obscured on purpose).
OwnerLangBackground.js loaded
Your public IP address is: xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xx
Your response is: Object { ip: "xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:…" }
Activating BLOCK 2 results in the error response.
OwnerLangBackground.js loaded
Something went wrong. 0
However, if I call the two URLs using curl directly, they both return valid JSON:
> curl https://mathiasbynens.be/demo/ip
{"ip":"xxxx:xxxx:xxxx::xxx"}
> curl http://ec2-35-158-91-62.eu-central-1.compute.amazonaws.com:9000/get-languages
[{"language":"??"},{"language":"de"},{"language":"en"},{"language":"fr"},{"language":"it"}]
I have added debugging output to my rest service on the AWS server and I see that it gets called. I also traced the WebExtension call to the rest service using Wireshark on my local machine on which the WebExtension is running and I can see the JSON string being returned, so I am guessing that the error occurs somewhere within firefox/the webextension, but I am at a total loss.
Things I have considered:
Permissions in the manifest: as far as I can tell the URL pattern for my aws-url is correctly added. However, the call to mathiasbynens.be works even though I have not added the url to the permissions
the call that works uses https while the call that does not work uses http. Could this be the reason?
Can anyone point me in the right direction to get more feedback on what goes wrong? I've tried adding a onerror callback to the xhr request. It is called but as far as I can see doesn't provide more information.
UPDATE:
I've come up with two more ideas. Using curl -v provided me with the headers:
> curl -v http://ec2-35-158-91-62.eu-central-1.compute.amazonaws.com:9000/get-languages
* Hostname was NOT found in DNS cache
* Trying 35.158.91.62...
* Connected to ec2-35-158-91-62.eu-central-1.compute.amazonaws.com (35.158.91.62) port 9000 (#0)
> GET /get-languages HTTP/1.1
> User-Agent: curl/7.38.0
> Host: ec2-35-158-91-62.eu-central-1.compute.amazonaws.com:9000
> Accept: */*
>
< HTTP/1.1 200
< Content-Type: application/json;charset=UTF-8
< Transfer-Encoding: chunked
< Date: Sun, 23 Apr 2017 06:43:42 GMT
<
* Connection #0 to host ec2-35-158-91-62.eu-central-1.compute.amazonaws.com left intact
[{"language":"??"},{"language":"de"},{"language":"en"},{"language":"fr"},{"language":"it"}]
> curl -v https://mathiasbynens.be/demo/ip
* Hostname was NOT found in DNS cache
* Trying 2a01:1b0:7999:402::144...
* Connected to mathiasbynens.be (2a01:1b0:7999:402::144) port 443 (#0)
* successfully set certificate verify locations:
* CAfile: none
CApath: /etc/ssl/certs
* SSLv3, TLS handshake, Client hello (1):
* SSLv3, TLS handshake, Server hello (2):
* SSLv3, TLS handshake, CERT (11):
* SSLv3, TLS handshake, Server key exchange (12):
* SSLv3, TLS handshake, Server finished (14):
* SSLv3, TLS handshake, Client key exchange (16):
* SSLv3, TLS change cipher, Client hello (1):
* SSLv3, TLS handshake, Finished (20):
* SSLv3, TLS change cipher, Client hello (1):
* SSLv3, TLS handshake, Finished (20):
* SSL connection using TLSv1.2 / ECDHE-RSA-AES128-GCM-SHA256
* Server certificate:
* subject: OU=Domain Control Validated; OU=PositiveSSL Wildcard; CN=*.mathiasbynens.be
* start date: 2015-07-28 00:00:00 GMT
* expire date: 2018-08-12 23:59:59 GMT
* subjectAltName: mathiasbynens.be matched
* issuer: C=GB; ST=Greater Manchester; L=Salford; O=COMODO CA Limited; CN=COMODO RSA Domain Validation Secure Server CA
* SSL certificate verify ok.
> GET /demo/ip HTTP/1.1
> User-Agent: curl/7.38.0
> Host: mathiasbynens.be
> Accept: */*
>
< HTTP/1.1 200 OK
< Date: Sun, 23 Apr 2017 06:44:16 GMT
* Server Apache is not blacklisted
< Server: Apache
< Access-Control-Allow-Origin: *
< Strict-Transport-Security: max-age=15768000; includeSubDomains
< Vary: Accept-Encoding
< Cache-Control: max-age=0
< Expires: Sun, 23 Apr 2017 06:44:16 GMT
< X-UA-Compatible: IE=edge
< X-Content-Type-Options: nosniff
< X-Frame-Options: DENY
< X-XSS-Protection: 1; mode=block
< Transfer-Encoding: chunked
< Content-Type: application/json;charset=UTF-8
<
* Connection #0 to host mathiasbynens.be left intact
{"ip":"xxxx:xxxx:xxxx::xxx"}
The one difference that stuck out was that my rest service's response lacks the Transfer-Encoding and Access-Control-Allow-Origin? headers, so I'll look into adding those.
Still, if anyone has a hint on how to get more error information for what goes wrong with XmlHttpRequest I'd be glad to hear it.
Ok, it seems the missing Access-Control-Allow-Origin? header was the root of my problems.
I have now changed all methods in my Spring-RestControllers by adding another method parameter HttpServletResponse response and then calling setHeader() on that parameter.
#RequestMapping("/get-languages")
public #ResponseBody List<Language> getLanguages(HttpServletResponse response) {
response.setHeader("Content-Type", "application/json;charset=UTF-8");
response.setHeader("Access-Control-Allow-Origin", "*");
return languageRepository.findAll();
}
Now my WebExtension can use this rest service sucessfully using XmlHttpRequest.
It would have been helpful if this information (that the CORS header was missing) had been visible somewhere in firefox's debugging or js console, so if anyone can tell me how I could have seen this, I'd still appreciate a hint.

res.json express not working

I'm trying to run a simple response.json() with express but it doesn't make the json itself.
The node.js file: server/app.js
"use strict";
let express = require('express');
let app = express();
app.use(express.static(__dirname + "/../client"));
app.get('/sports', function(request, response) {
response.json( ["Cycling", "Weightlifting"] );
});
app.listen(8181, () => console.log("Listening on 8181"));
The terminal runing the server:
$ node app.js
Listening on 8181
The "test" for the response.json():
$ curl -i localhost:8181/sports
HTTP/1.1 404 Not Found
X-Powered-By: Express
X-Content-Type-Options: nosniff
Content-Type: text/html; charset=utf-8
Content-Length: 19
Date: Fri, 10 Jun 2016 20:23:17 GMT
Connection: keep-alive
Cannot GET /sports
I really don't know what is going on because this is an example of a video in codeschool and is a copy of this git commit and everything looks the same :( https://github.com/codeschool/OlympicsMEAN/commit/767c89b8b0025861cefac910f98d79ef52cb3497
Thanks

Cannot receive JSON exception message/content type on remote requests

I have a ASP.NET MVC3 application, which uses JSON to comunicate with a Flash UI.
I´m use an ActionFilterAttribute to handle JSON exceptions (from Handle JSON Exceptions Gracefully in ASP.NET MVC 2: http://www.dotnetcurry.com/ShowArticle.aspx?ID=496):
public class HandleJsonExceptionAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
if (filterContext.Exception != null)
{
filterContext.HttpContext.Response.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError;
filterContext.Result = new JsonResult()
{
JsonRequestBehavior = JsonRequestBehavior.AllowGet,
Data = new
{
filterContext.Exception.Message,
}
};
filterContext.ExceptionHandled = true;
}
}
}
It´s works ok when executes on localhost, details from fiddler:
HTTP/1.1 500 Internal Server Error
Cache-Control: private
Content-Type: application/json; charset=utf-8
Server: Microsoft-IIS/7.5
X-AspNetMvc-Version: 3.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Mon, 11 Apr 2011 19:05:21 GMT
Content-Length: 34
{"Message":"No está autenticado"}
But, when executed from remote clients, on the LAN for example, I get the response in "Content-Type: text/html" instead "Content-Type: application/json;" and the content is a standard html error page:
500 - Internal server error.
There is a problem with the resource you are looking for, and it cannot be displayed.
HTTP/1.1 500 Internal Server Error
Cache-Control: private
Content-Type: text/html
Server: Microsoft-IIS/7.5
X-AspNetMvc-Version: 3.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Mon, 11 Apr 2011 19:07:53 GMT
Content-Length: 1208
What or where I need to configure something to get the JSON response on remote requests?
I need the flash UI receive a http 500 error, but with the json message instead the html.
Looking at the article the javascript only seems to be wire up for local requests.
What you need is to be using jsonp. (json with padding). This will allow you to do proper cross domain request returning a json object.
Further info can be found here and here.
I had a same problem, I solved with this code in web.config
<httpErrors existingResponse="PassTrough"></httpErrors>