Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hyperledger Sawtooth - Preflight error while submitting transaction

I am trying to submit a transaction to Hyperledger Sawtooth v1.0.1 using javascript to a validator running on localhost. The code for the post request is as below:

request.post({
        url: constants.API_URL + '/batches',
        body: batchListBytes,
        headers: { 'Content-Type': 'application/octet-stream' }
    }, (err, response) => {
        if (err) {
            console.log(err);
            return cb(err)
        }
        console.log(response.body);
        return cb(null, response.body);
    });

The transaction gets processed when submitted from an backend nodejs application, but it returns an OPTIONS http://localhost:8080/batches 405 (Method Not Allowed) error when submitted from client. These are the options that I have tried:

  1. Inject Access-Control-Allow-* headers into the response using an extension: The response still gives the same error
  2. Remove the custom header to bypass preflight request: This makes the validator throw an error as shown:

    ...
    sawtooth-rest-api-default | KeyError: "Key not found: 'Content-Type'"
    sawtooth-rest-api-default | [2018-03-15 08:07:37.670 ERROR    web_protocol] Error handling request
    sawtooth-rest-api-default | Traceback (most recent call last):
    ...
    

The unmodified POST request from the browser gets the following response headers from the validator:

HTTP/1.1 405 Method Not Allowed
Content-Type: text/plain; charset=utf-8
Allow: GET,HEAD,POST
Content-Length: 23
Date: Thu, 15 Mar 2018 08:42:01 GMT
Server: Python/3.5 aiohttp/2.3.2

So, I guess OPTIONS method is not handled in the validator. A GET request for the state goes through fine when the CORS headers are added. This issue was also not faced in Sawtooth v0.8.

I am using docker to start the validator, and the commands to start it are a slightly modified version of those given in the LinuxFoundationX: LFS171x course. The relevant commands are below:

bash -c \"\
        sawadm keygen && \
        sawtooth keygen my_key && \
        sawset genesis -k /root/.sawtooth/keys/my_key.priv && \
        sawadm genesis config-genesis.batch && \
        sawtooth-validator -vv \
          --endpoint tcp://validator:8800 \
          --bind component:tcp://eth0:4004 \
          --bind network:tcp://eth0:8800

Can someone please guide me as to how to solve this problem?

like image 589
KBhokray Avatar asked Mar 06 '23 16:03

KBhokray


1 Answers

CORS issues are always the best.

What is CORS?

Your browser trying to protect users from bring directed to a page they think is the frontend for an API, but is actually fraudulent. Anytime a web page tries to access an API on a different domain, that API will need to explicitly give the webpage permission, or the browser will block the request. This is why you can query the API from Node.js (no browser), and can put the REST API address directly into your address bar (same domain). However, trying to go from localhost:3000 to localhost:8008 or from file://path/to/your/index.html to localhost:8008 is going to get blocked.

Why doesn't the Sawtooth REST API handle OPTIONS requests?

The Sawtooth REST API does not know the domain you are going to run your web page from, so it can't whitelist it explicitly. It is possible to whitelist all domains, but this obviously destroys any protection CORS might give you. Rather than try to weigh the costs and benefits of this approach for all Sawtooth users everywhere, the decision was made to make the REST API as lightweight and security agnostic as possible. Any developer using it would be expected to put it behind a proxy server, and they can make whatever security decisions they need on that proxy layer.

So how do you fix it?

You need to setup a proxy server that will put the REST API and your web page on the same domain. There is no quick configuration option for this. You will have to set up an actual server. Obviously there are lots of ways to do this. If you are already familiar with Node, you could serve the page from Node.js, and then have the Node server proxy the API calls. If you are already running all of the Sawtooth components with docker-compose though, it might be easier to use Docker and Apache.

Setting up an Apache Proxy with Docker

Create your Dockerfile

In the same directory as your web app create a text file called "Dockerfile" (no extension). Then make it look like this:

FROM httpd:2.4

RUN echo "\
LoadModule proxy_module modules/mod_proxy.so\n\
LoadModule proxy_http_module modules/mod_proxy_http.so\n\
ProxyPass /api http://rest-api:8008\n\
ProxyPassReverse /api http://rest-api:8008\n\
RequestHeader set X-Forwarded-Path \"/api\"\n\
" >>/usr/local/apache2/conf/httpd.conf

This is going to do a couple of things. First it will pull down the httpd module from DockerHub, which is just a simple static server. Then we are using a bit of bash to add five lines to Apache's configuration file. These five lines import the proxy modules, tell Apache that we want to proxy http://rest-api:8008 to the /api route, and set the X-Forwarded-Path header so the REST API can properly build response URLs. Make sure that rest-api matches the actual name of the Sawtooth REST API service in your docker compose file.

Modify your docker compose file

Now, to the docker compose YAML file you are running Sawtooth through, you want to add a new property under the services key:

services:
  my-web-page:
    build: ./path/to/web/dir/
    image: my-web-page
    container_name: my-web-page
    volumes:
      - ./path/to/web/dir/public/:/usr/local/apache2/htdocs/
    expose:
      - 80
    ports:
      - '8000:80'
    depends_on:
      - rest-api

This will build your Dockerfile located at ./path/to/web/dir/Dockerfile (relative to the docker compose file), and run it with its default command, which is to start up Apache. Apache will serve whatever files are located in /usr/local/apache2/htdocs/, so we'll use volumes to link the path to your web files on your host machine (i.e. ./path/to/web/dir/public/), to that directory in the container. This is basically an alias, so if you update your web app later, you don't need to restart this docker container to see the changes. Finally, ports will take the server, which is at port 80 inside the container, and forward it out to localhost:8000.

Running it all

Now you should be able to run:

docker-compose -f path/to/your/compose-file.yaml up

And it will start up your Apache server along with the Sawtooth REST API and validator and any other services you defined. If you go to http://localhost:8000, you should see your web page, and if you go to http://localhost:8000/api/blocks, you should see a JSON representation of the blocks on chain. More importantly you should be able to make the request from your web app:

request.post({
    url: 'api/batches',
    body: batchListBytes,
    headers: { 'Content-Type': 'application/octet-stream' }
}, (err, response) => console.log(response) );

Whew. Sorry for the long response, but I'm not sure if it is possible to solve CORS any faster. Hopefully this helps.

like image 167
Zac Delventhal Avatar answered May 16 '23 07:05

Zac Delventhal