grin/api/tests/rest.rs
hashmap 972c2e5aa9
Support TLS in ApiServer (#1565)
* Support TLS in ApiServer

This is ground work to support TLS in Grin APIs (like wallet ot node). Particular API implemention needs to decide if TLS is used or not and pass certificate data etc.

* P12 format support
* New method to start TLS server
* Transparent TLS support in API client (depends on URL scheme http/https)
* Refactoring
* Initial support for graceful shutdown (commentred out int this PR, unstable for now)
* API server tests (TLS server test is disabled by default, hyper client rejects self-signed certificates, so extra step is needed to install local CA (I used mkcert)
* Add a cert file to make test complile
2018-09-21 13:33:23 +02:00

68 lines
2.1 KiB
Rust

extern crate grin_api as api;
extern crate grin_util as util;
extern crate hyper;
use api::*;
use hyper::{Body, Request};
use std::net::SocketAddr;
use std::{thread, time};
struct IndexHandler {
list: Vec<String>,
}
impl IndexHandler {}
impl Handler for IndexHandler {
fn get(&self, _req: Request<Body>) -> ResponseFuture {
json_response_pretty(&self.list)
}
}
fn build_router() -> Router {
let route_list = vec!["get blocks".to_string(), "get chain".to_string()];
let index_handler = IndexHandler { list: route_list };
let mut router = Router::new();
router
.add_route("/v1/*", Box::new(index_handler))
.expect("add_route failed");
router
}
#[test]
fn test_start_api() {
util::init_test_logger();
let mut server = ApiServer::new();
let router = build_router();
let server_addr = "127.0.0.1:14434";
let addr: SocketAddr = server_addr.parse().expect("unable to parse server address");
assert!(server.start(addr, router));
let url = format!("http://{}/v1/", server_addr);
let index = api::client::get::<Vec<String>>(url.as_str()).unwrap();
assert_eq!(index.len(), 2);
assert!(server.stop());
thread::sleep(time::Duration::from_millis(1_000));
}
// To enable this test you need a trusted PKCS12 (p12) certificate bundle
// Hyper-tls client doesn't accept self-signed certificates. The easiest way is to use mkcert
// https://github.com/FiloSottile/mkcert to install CA and generate a certificate on your local machine.
// You need to put the file to api/tests folder
#[ignore]
#[test]
fn test_start_api_tls() {
util::init_test_logger();
let tls_conf = TLSConfig {
pkcs_bytes: include_bytes!("localhost+1.p12").to_vec(),
pass: "changeit".to_string(),
};
let mut server = ApiServer::new();
let router = build_router();
let server_addr = "127.0.0.1:14444";
let addr: SocketAddr = server_addr.parse().expect("unable to parse server address");
assert!(server.start_tls(addr, router, tls_conf));
let url = format!("https://{}/v1/", server_addr);
let index = api::client::get::<Vec<String>>(url.as_str()).unwrap();
assert_eq!(index.len(), 2);
assert!(!server.stop());
}