Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Native CORS support for defichain #330

Merged
merged 3 commits into from
Apr 21, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions src/httprpc.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,8 @@ class HTTPRPCTimerInterface : public RPCTimerInterface
static std::string strRPCUserColonPass;
/* Stored RPC timer interface (for unregistration) */
static std::unique_ptr<HTTPRPCTimerInterface> httpRPCTimerInterface;
/* The host to be used for CORS header */
static std::string corsOriginHost;

static void JSONErrorReply(HTTPRequest* req, const UniValue& objError, const UniValue& id)
{
Expand Down Expand Up @@ -144,8 +146,35 @@ static bool RPCAuthorized(const std::string& strAuth, std::string& strAuthUserna
return multiUserAuthorized(strUserPass);
}

static bool CorsHandler(HTTPRequest *req) {
auto host = corsOriginHost;
// If if it's empty assume cors is disallowed. Do nothing and proceed,
// with request as usual.
if (host.empty())
return false;

req->WriteHeader("Access-Control-Allow-Origin", host);
req->WriteHeader("Access-Control-Allow-Credentials", "true");
req->WriteHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
req->WriteHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");

// If it's a Cors preflight request, short-circuit and return. We have
// set what's needed already.
if (req->GetRequestMethod() == HTTPRequest::OPTIONS) {
req->WriteReply(HTTP_NO_CONTENT);
return true;
}

// Indicate to continue with the request as usual
return false;
}

static bool HTTPReq_JSONRPC(HTTPRequest* req, const std::string &)
{
// Handle CORS
if (CorsHandler(req))
return true;

// JSONRPC handles only POST
if (req->GetRequestMethod() != HTTPRequest::POST) {
req->WriteReply(HTTP_BAD_METHOD, "JSONRPC server handles only POST requests");
Expand Down Expand Up @@ -239,6 +268,9 @@ bool StartHTTPRPC()
if (!InitRPCAuthentication())
return false;

// Setup Cors origin host name from arg.
corsOriginHost = gArgs.GetArg("-rpcallowcors", "");

RegisterHTTPHandler("/", true, HTTPReq_JSONRPC);
if (g_wallet_init_interface.HasWalletSupport()) {
RegisterHTTPHandler("/wallet/", false, HTTPReq_JSONRPC);
Expand Down
11 changes: 11 additions & 0 deletions src/httpserver.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,9 @@ static std::string RequestMethodString(HTTPRequest::RequestMethod m)
case HTTPRequest::PUT:
return "PUT";
break;
case HTTPRequest::OPTIONS:
return "OPTIONS";
break;
default:
return "unknown";
}
Expand Down Expand Up @@ -386,9 +389,14 @@ bool InitHTTPServer()
return false;
}

// Defaults + OPTIONS
auto allowed_methods = EVHTTP_REQ_GET | EVHTTP_REQ_HEAD | EVHTTP_REQ_POST;
allowed_methods |= EVHTTP_REQ_PUT | EVHTTP_REQ_DELETE | EVHTTP_REQ_OPTIONS;

evhttp_set_timeout(http, gArgs.GetArg("-rpcservertimeout", DEFAULT_HTTP_SERVER_TIMEOUT));
evhttp_set_max_headers_size(http, MAX_HEADERS_SIZE);
evhttp_set_max_body_size(http, MAX_DESER_SIZE);
evhttp_set_allowed_methods(http, allowed_methods);
evhttp_set_gencb(http, http_request_cb, nullptr);

if (!HTTPBindAddresses(http)) {
Expand Down Expand Up @@ -632,6 +640,9 @@ HTTPRequest::RequestMethod HTTPRequest::GetRequestMethod() const
case EVHTTP_REQ_PUT:
return PUT;
break;
case EVHTTP_REQ_OPTIONS:
return OPTIONS;
break;
default:
return UNKNOWN;
break;
Expand Down
3 changes: 2 additions & 1 deletion src/httpserver.h
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,8 @@ class HTTPRequest
GET,
POST,
HEAD,
PUT
PUT,
OPTIONS,
};

/** Get requested URI.
Expand Down
1 change: 1 addition & 0 deletions src/init.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -581,6 +581,7 @@ void SetupServerArgs()
gArgs.AddArg("-rpcuser=<user>", "Username for JSON-RPC connections", ArgsManager::ALLOW_ANY, OptionsCategory::RPC);
gArgs.AddArg("-rpcworkqueue=<n>", strprintf("Set the depth of the work queue to service RPC calls (default: %d)", DEFAULT_HTTP_WORKQUEUE), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::RPC);
gArgs.AddArg("-server", "Accept command line and JSON-RPC commands", ArgsManager::ALLOW_ANY, OptionsCategory::RPC);
gArgs.AddArg("-rpcallowcors=<host>", "Allow CORS requests from the given host origin. Include scheme and port (eg: -rpcallowcors=http://127.0.0.1:5000)", ArgsManager::ALLOW_ANY, OptionsCategory::RPC);

#if HAVE_DECL_DAEMON
gArgs.AddArg("-daemon", "Run in the background as a daemon and accept commands", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
Expand Down
1 change: 1 addition & 0 deletions src/rpc/protocol.h
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
enum HTTPStatusCode
{
HTTP_OK = 200,
HTTP_NO_CONTENT = 204,
HTTP_BAD_REQUEST = 400,
HTTP_UNAUTHORIZED = 401,
HTTP_FORBIDDEN = 403,
Expand Down
50 changes: 50 additions & 0 deletions test/functional/interface_http_cors.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
#!/usr/bin/env python3
# Copyright (c) 2014-2019 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file LICENSE or http://www.opensource.org/licenses/mit-license.php.
"""Test the RPC HTTP CORS."""

from test_framework.test_framework import DefiTestFramework
from test_framework.util import assert_equal, str_to_b64str

import http.client
import urllib.parse

class HTTPCorsTest (DefiTestFramework):
def set_test_params(self):
self.num_nodes = 1
self.cors_origin = "http://localhost:8000"
self.extra_args = [["-rpcallowcors=" + self.cors_origin]]

def run_test(self):

url = urllib.parse.urlparse(self.nodes[0].url)
authpair = url.username + ':' + url.password

#same should be if we add keep-alive because this should be the std. behaviour
headers = {"Authorization": "Basic " + str_to_b64str(authpair), "Connection": "keep-alive"}

conn = http.client.HTTPConnection(url.hostname, url.port)
conn.connect()
conn.request('POST', '/', '{"method": "getbestblockhash"}', headers)
res = conn.getresponse()
self.check_cors_headers(res)
assert_equal(res.status, http.client.OK)
res.close()


conn.request('OPTIONS', '/', '{"method": "getbestblockhash"}', headers)
res = conn.getresponse()
self.check_cors_headers(res)
assert_equal(res.status, http.client.NO_CONTENT)
res.close()

def check_cors_headers(self, res):
assert_equal(res.getheader("Access-Control-Allow-Origin"), self.cors_origin)
assert_equal(res.getheader("Access-Control-Allow-Credentials"), "true")
assert_equal(res.getheader("Access-Control-Allow-Methods"), "POST, GET, OPTIONS")
assert_equal(res.getheader("Access-Control-Allow-Headers"), "Content-Type, Authorization")


if __name__ == '__main__':
HTTPCorsTest ().main ()
1 change: 1 addition & 0 deletions test/functional/test_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,7 @@
'feature_mine_cached.py',
'feature_mempool_dakota.py',
'interface_http.py',
'interface_http_cors.py',
'interface_rpc.py',
'rpc_psbt.py',
'rpc_users.py',
Expand Down