use std::io::{Read, Write};
use std::path::Path;
use std::process::{Child, Command, Stdio};
use std::sync::Arc;
use std::time::{Duration, Instant};
use hmac::{Hmac, Mac};
use sha2::Sha256;
use tokio_rustls::rustls::pki_types::ServerName;
use tokio_rustls::rustls::{ClientConfig, ClientConnection, RootCertStore, StreamOwned, crypto};
const BINARY: &str = env!("CARGO_BIN_EXE_tinystore");
const HELLO: u8 = 1;
const WELCOME: u8 = 2;
const REQUEST: u8 = 3;
const RESPONSE: u8 = 4;
const GOAWAY: u8 = 10;
const END: u8 = 1;
const ERROR: u8 = 2;
const ADMIN: &str = "4dGQ6tR2kq0SxVZpLWn8E1yHf7cJmB3aUoN9Tz5Ki0E";
const DATA: &str = "Yq8wHn2xLz5Rb7Tc0Vm3Kj6Fd9Gs1Ap4Ue8Wo2Ni5Qt";
const SERVER_STOP: u16 = 0x0001;
fn frame(kind: u8, flags: u8, method: u16, stream: u32, body: &[u8]) -> Vec<u8> {
let mut bytes = Vec::with_capacity(12 + body.len());
bytes.extend_from_slice(&u32::try_from(body.len()).unwrap().to_le_bytes());
bytes.extend_from_slice(&[kind, flags]);
bytes.extend_from_slice(&method.to_le_bytes());
bytes.extend_from_slice(&stream.to_le_bytes());
bytes.extend_from_slice(body);
bytes
}
fn hello(challenge: Option<&[u8; 16]>) -> Vec<u8> {
let body = match challenge {
None => vec![0x81, 0x01, 0x01],
Some(challenge) => [&[0x82, 0x01, 0x01, 0x06, 0xc4, 0x10][..], challenge].concat(),
};
frame(HELLO, 0, 0, 0, &body)
}
fn hello_with(token: &str) -> Vec<u8> {
let body = [&[0x82, 0x01, 0x01, 0x03, 0xd9, u8::try_from(token.len()).unwrap()][..], token.as_bytes()].concat();
frame(HELLO, 0, 0, 0, &body)
}
fn holds(body: &[u8], text: &str) -> bool {
body.windows(text.len()).any(|window| window == text.as_bytes())
}
fn read_frame(reader: &mut impl Read) -> (u8, u8, u32, Vec<u8>) {
try_frame(reader).unwrap()
}
fn try_frame(reader: &mut impl Read) -> std::io::Result<(u8, u8, u32, Vec<u8>)> {
let mut header = [0; 12];
reader.read_exact(&mut header)?;
let length = u32::from_le_bytes(header[0..4].try_into().unwrap()) as usize;
let stream = u32::from_le_bytes(header[8..12].try_into().unwrap());
let mut body = vec![0; length];
reader.read_exact(&mut body)?;
Ok((header[4], header[5], stream, body))
}
fn logged_frame(reader: &mut impl Read, log: &Path) -> (u8, u8, u32, Vec<u8>) {
try_frame(reader).unwrap_or_else(|error| {
panic!("{error}; the server logged: {}", std::fs::read_to_string(log).unwrap_or_default())
})
}
fn wait(child: &mut Child) -> i32 {
let deadline = Instant::now() + Duration::from_secs(15);
loop {
if let Some(status) = child.try_wait().unwrap() {
return status.code().unwrap_or(-1);
}
assert!(Instant::now() < deadline, "the server did not exit");
std::thread::sleep(Duration::from_millis(20));
}
}
#[test]
fn a_server_started_with_a_durability_opens_its_store_with_it_and_says_so() {
let dir = tempfile::tempdir().unwrap();
let mut child = Command::new(BINARY)
.args(["serve", "--dir"])
.arg(dir.path())
.args(["--stdio", "--durability", "os"])
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn()
.unwrap();
child.stdin.as_mut().unwrap().write_all(&hello(None)).unwrap();
let (kind, _, _, welcome) = read_frame(child.stdout.as_mut().unwrap());
assert_eq!(kind, WELCOME);
assert!(
welcome.windows(4).any(|window| window == [12, 0xa2, b'o', b's']),
"the WELCOME names the store's durability"
);
drop(child.stdin.take());
assert_eq!(wait(&mut child), 0);
}
#[test]
fn a_private_child_answers_hello_and_leaves_when_its_stdin_ends() {
let dir = tempfile::tempdir().unwrap();
let mut child = Command::new(BINARY)
.args(["serve", "--dir"])
.arg(dir.path())
.arg("--stdio")
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn()
.unwrap();
child.stdin.as_mut().unwrap().write_all(&hello(None)).unwrap();
let (kind, ..) = read_frame(child.stdout.as_mut().unwrap());
assert_eq!(kind, WELCOME);
drop(child.stdin.take());
assert_eq!(wait(&mut child), 0, "the end of stdin asks it to leave");
}
#[test]
fn a_local_server_publishes_serve_proves_itself_stops_and_holds_its_directory_meanwhile() {
let (dir, logs) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
let log = logs.path().join("serve.log");
let mut server = Command::new(BINARY)
.args(["serve", "--dir"])
.arg(dir.path())
.args(["--local", "--idle", "0ms", "--log-file"])
.arg(&log)
.stderr(Stdio::null())
.spawn()
.unwrap();
let serve = published(&dir.path().join("server").join("SERVE"));
assert_eq!(serve["protocol"], 1);
assert_eq!(serve["sidecar"], true);
let held =
Command::new(BINARY).args(["serve", "--dir"]).arg(dir.path()).arg("--local").stderr(Stdio::null()).status();
assert_eq!(held.unwrap().code(), Some(3), "a second server finds the directory held");
let mut client = connect(serve["endpoints"][0].as_str().unwrap());
let challenge = *b"0123456789abcdef";
client.write_all(&hello(Some(&challenge))).unwrap();
let (kind, _, _, welcome) = logged_frame(&mut client, &log);
assert_eq!(kind, WELCOME);
let secret = base64url(serve["secret"].as_str().unwrap());
let mut mac = Hmac::<Sha256>::new_from_slice(&secret).unwrap();
mac.update(&challenge);
let proof = &welcome[welcome.len() - 35..];
assert_eq!(&proof[..3], &[0x0b, 0xc4, 0x20], "the proof is WELCOME's last field, 32 bytes");
assert_eq!(&proof[3..], &mac.finalize().into_bytes()[..]);
client.write_all(&frame(REQUEST, END, SERVER_STOP, 1, &[0x80])).unwrap();
let (kind, flags, stream, _) = logged_frame(&mut client, &log);
assert_eq!((kind, flags & END, stream), (RESPONSE, END, 1));
assert_eq!(wait(&mut server), 0);
assert!(!dir.path().join("server").join("SERVE").exists(), "SERVE goes before the directory is let go");
}
fn remote(dir: &Path, listen: &str, tls: &[&Path]) -> (Child, serde_json::Value) {
let tokens = dir.join("tokens");
std::fs::write(&tokens, format!("# who may connect\nadmin {ADMIN}\ndata {DATA}\n")).unwrap();
let mut command = Command::new(BINARY);
command.arg("serve").arg(dir.join("store")).args(["--listen", listen, "--tokens"]).arg(&tokens);
if let [cert, key] = tls {
command.arg("--tls-cert").arg(cert).arg("--tls-key").arg(key);
}
let server = command.stderr(Stdio::null()).spawn().unwrap();
let serve = published(&dir.join("store").join("server").join("SERVE"));
(server, serve)
}
#[test]
fn a_remote_client_is_admitted_by_its_token_and_may_do_what_its_line_says() {
let dir = tempfile::tempdir().unwrap();
let (mut server, serve) = remote(dir.path(), "tcp://127.0.0.1:0", &[]);
let endpoint = serve["endpoints"][1].as_str().unwrap();
let address = endpoint.strip_prefix("tcp://").unwrap();
let mut stranger = std::net::TcpStream::connect(address).unwrap();
stranger.write_all(&hello(None)).unwrap();
let (kind, _, _, body) = read_frame(&mut stranger);
assert!(kind == GOAWAY && holds(&body, "unauthenticated"), "no token");
let mut data = std::net::TcpStream::connect(address).unwrap();
data.write_all(&hello_with(DATA)).unwrap();
let (kind, _, _, welcome) = read_frame(&mut data);
assert!(kind == WELCOME && holds(&welcome, "data"));
data.write_all(&frame(REQUEST, END, SERVER_STOP, 1, &[0x80])).unwrap();
let (_, flags, _, refused) = read_frame(&mut data);
assert!(flags & ERROR != 0 && holds(&refused, "permission"), "a data client cannot stop the server");
let mut admin = std::net::TcpStream::connect(address).unwrap();
admin.write_all(&hello_with(ADMIN)).unwrap();
let (kind, _, _, welcome) = read_frame(&mut admin);
assert!(kind == WELCOME && holds(&welcome, "admin"));
admin.write_all(&frame(REQUEST, END, SERVER_STOP, 1, &[0x80])).unwrap();
assert_eq!(read_frame(&mut admin).0, RESPONSE);
assert_eq!(wait(&mut server), 0);
}
#[test]
fn a_tls_server_answers_over_its_certificate() {
let dir = tempfile::tempdir().unwrap();
let certified = rcgen::generate_simple_self_signed(vec!["localhost".to_owned()]).unwrap();
let (cert, key) = (dir.path().join("cert.pem"), dir.path().join("key.pem"));
std::fs::write(&cert, certified.cert.pem()).unwrap();
std::fs::write(&key, certified.signing_key.serialize_pem()).unwrap();
let (mut server, serve) = remote(dir.path(), "tls://127.0.0.1:0", &[&cert, &key]);
let endpoint = serve["endpoints"][1].as_str().unwrap();
assert!(endpoint.starts_with("tls://127.0.0.1:"), "{endpoint}");
let mut roots = RootCertStore::empty();
roots.add(certified.cert.der().clone()).unwrap();
let config = ClientConfig::builder_with_provider(Arc::new(crypto::ring::default_provider()))
.with_safe_default_protocol_versions()
.unwrap()
.with_root_certificates(roots)
.with_no_client_auth();
let tcp = std::net::TcpStream::connect(endpoint.strip_prefix("tls://").unwrap()).unwrap();
let connection = ClientConnection::new(Arc::new(config), ServerName::try_from("localhost").unwrap()).unwrap();
let mut tls = StreamOwned::new(connection, tcp);
tls.write_all(&hello_with(ADMIN)).unwrap();
assert_eq!(read_frame(&mut tls).0, WELCOME);
tls.write_all(&frame(REQUEST, END, SERVER_STOP, 1, &[0x80])).unwrap();
assert_eq!(read_frame(&mut tls).0, RESPONSE);
assert_eq!(wait(&mut server), 0);
}
#[test]
fn a_connection_that_says_no_hello_ends_with_the_handshakes_time() {
let dir = tempfile::tempdir().unwrap();
let (mut server, serve) = remote(dir.path(), "tcp://127.0.0.1:0", &[]);
let address = serve["endpoints"][1].as_str().unwrap().strip_prefix("tcp://").unwrap().to_owned();
let mut silent = std::net::TcpStream::connect(&address).unwrap();
let began = Instant::now();
let mut byte = [0];
let read = silent.read(&mut byte);
assert!(matches!(read, Ok(0) | Err(_)), "the server ended the connection: {read:?}");
assert!(began.elapsed() < Duration::from_secs(10), "after {:?}", began.elapsed());
let mut admin = std::net::TcpStream::connect(&address).unwrap();
admin.write_all(&hello_with(ADMIN)).unwrap();
assert_eq!(read_frame(&mut admin).0, WELCOME);
admin.write_all(&frame(REQUEST, END, SERVER_STOP, 1, &[0x80])).unwrap();
assert_eq!(read_frame(&mut admin).0, RESPONSE);
assert_eq!(wait(&mut server), 0);
}
#[test]
fn a_mistake_in_the_tokens_leaves_no_files_behind() {
let dir = tempfile::tempdir().unwrap();
let tokens = dir.path().join("tokens");
std::fs::write(&tokens, "admin short\n").unwrap();
let store = dir.path().join("store");
let status = Command::new(BINARY)
.arg("serve")
.arg(&store)
.args(["--listen", "tcp://127.0.0.1:0", "--tokens"])
.arg(&tokens)
.stderr(Stdio::null())
.status()
.unwrap();
assert_eq!(status.code(), Some(1));
assert!(!store.exists(), "the store never opened");
}
#[test]
fn status_finds_a_running_server_and_stop_stops_it_its_serve_gone() {
let dir = tempfile::tempdir().unwrap();
let mut server = Command::new(BINARY).arg("serve").arg(dir.path()).stderr(Stdio::null()).spawn().unwrap();
published(&dir.path().join("server").join("SERVE"));
let status = Command::new(BINARY).arg("status").arg(dir.path()).output().unwrap();
let said = String::from_utf8_lossy(&status.stdout);
assert!(status.status.success() && said.contains("served by tinystore"), "{said}");
let stop = Command::new(BINARY).arg("stop").arg(dir.path()).output().unwrap();
let said = format!("{}{}", String::from_utf8_lossy(&stop.stdout), String::from_utf8_lossy(&stop.stderr));
assert!(stop.status.success() && said.contains("stopped"), "{said}");
assert!(!dir.path().join("server").join("SERVE").exists(), "SERVE is gone once stop returns");
assert_eq!(wait(&mut server), 0);
let status = Command::new(BINARY).arg("status").arg(dir.path()).output().unwrap();
assert!(String::from_utf8_lossy(&status.stdout).contains("not served"));
let again = Command::new(BINARY).arg("stop").arg(dir.path()).output().unwrap();
assert_eq!(again.status.code(), Some(1), "no server to stop");
}
fn published(path: &Path) -> serde_json::Value {
let deadline = Instant::now() + Duration::from_secs(15);
loop {
if let Ok(text) = std::fs::read_to_string(path) {
return serde_json::from_str(&text).unwrap();
}
assert!(Instant::now() < deadline, "no SERVE");
std::thread::sleep(Duration::from_millis(20));
}
}
#[cfg(unix)]
fn connect(endpoint: &str) -> std::os::unix::net::UnixStream {
std::os::unix::net::UnixStream::connect(endpoint.strip_prefix("unix://").unwrap()).unwrap()
}
#[cfg(windows)]
fn connect(endpoint: &str) -> std::fs::File {
let name = format!(r"\\.\pipe\{}", endpoint.strip_prefix("pipe:").unwrap());
std::fs::OpenOptions::new().read(true).write(true).open(name).unwrap()
}
fn base64url(text: &str) -> Vec<u8> {
const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
let sextets: Vec<u32> =
text.bytes().map(|byte| ALPHABET.iter().position(|letter| *letter == byte).unwrap() as u32).collect();
let mut bytes = Vec::new();
for chunk in sextets.chunks(4) {
let joined = chunk.iter().enumerate().fold(0, |joined, (at, sextet)| joined | sextet << (18 - 6 * at));
bytes.extend((0..chunk.len() - 1).map(|at| (joined >> (16 - 8 * at)) as u8));
}
bytes
}