Your browser sucks, JavaScript disabled! Gunnar's console needs JavaScript and WebAssembly. Git over SSH on port 2222 does not.

nordisk/korp-map

crates/korp-map-wire/tests/https.rs

//! **The doors over HTTPS** (features `tls` + `client-tls`): a server with a self-signed
//! certificate answers the HTTP and Flight clients over TLS exactly as the plain port
//! answers them, and a client that does not trust the certificate gets no answer.

mod common;

use std::net::SocketAddr;
use std::sync::Arc;

use common::*;
use korp_map_wire::tls::{certified_key_from_pem, TlsDoor};
use korp_map_wire::{
    BBox, Code, FlightMapClient, GeocodeQuery, HttpMapClient, Kind, MapClient, MapQuery,
    RevGeocodeQuery, ServerConfig,
};

/// One source behind a plain port and an HTTPS port.
struct TwoPorts {
    plain: SocketAddr,
    tls: SocketAddr,
    cert_pem: String,
    _addresses: AddressServer,
}

impl TwoPorts {
    async fn start() -> Self {
        let addresses = AddressServer::start(ServerConfig::default()).await;
        let cert = rcgen::generate_simple_self_signed(vec!["localhost".into()]).unwrap();
        let key = certified_key_from_pem(
            cert.cert.pem().as_bytes(),
            cert.key_pair.serialize_pem().as_bytes(),
        )
        .unwrap();
        let door = Arc::new(TlsDoor::fixed(key));
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let tls = listener.local_addr().unwrap();
        let source = addresses.source.clone();
        tokio::spawn(async move {
            korp_map_wire::serve_tls(listener, door, source, ServerConfig::default()).await;
        });
        Self {
            plain: addresses.addr,
            tls,
            cert_pem: cert.cert.pem(),
            _addresses: addresses,
        }
    }

    fn https_base(&self) -> String {
        format!("https://localhost:{}", self.tls.port())
    }

    fn doors(&self) -> Vec<(&'static str, Box<dyn MapClient>)> {
        let tls = korp_map_wire::tls::client_config_trusting(self.cert_pem.as_bytes()).unwrap();
        vec![
            (
                "https",
                Box::new(HttpMapClient::with_tls(self.https_base(), tls)),
            ),
            (
                "flight over tls",
                Box::new(
                    FlightMapClient::with_tls_roots(self.https_base(), self.cert_pem.as_bytes())
                        .unwrap(),
                ),
            ),
        ]
    }

    fn plain(&self) -> HttpMapClient {
        HttpMapClient::new(format!("http://{}", self.plain))
    }
}

fn q(kind: Kind) -> MapQuery {
    MapQuery {
        region: REGION.to_string(),
        bbox: BBox::new(11.0, 55.0, 14.2, 57.1).unwrap(),
        lod: 12,
        kind,
        max: None,
    }
}

#[tokio::test(flavor = "multi_thread")]
async fn https_answers_health_regions_a_map_query_and_geocode_like_the_plain_port() {
    let s = TwoPorts::start().await;
    let plain = s.plain();
    let want_regions = plain.regions().await.unwrap();
    let gq = GeocodeQuery {
        region: REGION.to_string(),
        q: "storgatan 5 uppsala".to_string(),
        max: None,
    };
    let rq = RevGeocodeQuery {
        region: REGION.to_string(),
        lon: 14.5,
        lat: 61.0,
    };
    for (door, c) in s.doors() {
        c.health().await.unwrap_or_else(|e| panic!("{door}: {e}"));
        assert_eq!(c.regions().await.unwrap(), want_regions, "{door}");
        for kind in Kind::ALL {
            let want = plain.query(&q(kind)).await.unwrap();
            let got = c.query(&q(kind)).await.unwrap();
            assert!(got.num_rows() > 0, "{door} {kind}: rows");
            assert_eq!(got, want, "{door} {kind}: the same reply as the plain port");
        }
        let g = c.geocode(&gq).await.unwrap();
        assert_eq!(g, plain.geocode(&gq).await.unwrap(), "{door}");
        assert_eq!(g.hits[0].street, "Storgatan");
        let r = c.revgeocode(&rq).await.unwrap();
        assert_eq!(r, plain.revgeocode(&rq).await.unwrap(), "{door}");
    }
}

#[tokio::test(flavor = "multi_thread")]
async fn a_refusal_over_https_is_the_same_refusal() {
    let s = TwoPorts::start().await;
    let mut bad = q(Kind::Lines);
    bad.region = "atlantis".to_string();
    let want = s.plain().query(&bad).await.unwrap_err();
    assert_eq!(want.code, Code::UnknownRegion);
    for (door, c) in s.doors() {
        assert_eq!(c.query(&bad).await.unwrap_err(), want, "{door}");
    }
}

#[tokio::test(flavor = "multi_thread")]
async fn a_client_that_does_not_trust_the_certificate_gets_no_answer() {
    let s = TwoPorts::start().await;
    // The webpki roots do not hold a self-signed certificate.
    let e = HttpMapClient::new(s.https_base())
        .health()
        .await
        .unwrap_err();
    assert_eq!(e.code, Code::Unreachable, "{e}");
    let e = FlightMapClient::new(s.https_base())
        .unwrap()
        .health()
        .await
        .unwrap_err();
    assert_eq!(e.code, Code::Unreachable, "{e}");
}

#[tokio::test(flavor = "multi_thread")]
async fn plain_http_on_the_tls_port_is_dropped_and_the_port_keeps_serving() {
    let s = TwoPorts::start().await;
    let e = HttpMapClient::new(format!("http://{}", s.tls))
        .health()
        .await
        .unwrap_err();
    assert_eq!(e.code, Code::Unreachable, "{e}");
    let (_, c) = s.doors().remove(0);
    c.health().await.unwrap();
}