Initial commit

This commit is contained in:
2023-11-04 13:52:16 -05:00
commit ac9681e0c3
19 changed files with 3419 additions and 0 deletions

2
tests/common/mod.rs Normal file
View File

@@ -0,0 +1,2 @@
pub mod setup;
pub mod token;

71
tests/common/setup.rs Normal file
View File

@@ -0,0 +1,71 @@
use std::error::Error;
use std::io::prelude::*;
use std::path::Path;
use std::sync::Once;
use rand_core::OsRng;
use ssh_key::{Algorithm, Fingerprint, PrivateKey, PublicKey};
use tempfile::NamedTempFile;
use tracing_subscriber::EnvFilter;
use sshca::config::Configuration;
static INIT: Once = Once::new();
fn gen_machine_ids() -> Result<NamedTempFile, Box<dyn Error>> {
let f = NamedTempFile::new()?;
let map = serde_json::json!({
"test.example.org": "b75e9126-d73a-4ae0-9a0d-63cb3552e6cd",
});
serde_json::to_writer(&f, &map)?;
Ok(f)
}
fn gen_config(machine_ids: &Path, host_key: &Path) -> Configuration {
let mut config = Configuration {
machine_ids: machine_ids.to_str().unwrap().into(),
..Default::default()
};
config.ca.host.private_key_file = host_key.to_str().unwrap().into();
config
}
fn gen_ca_key() -> Result<(NamedTempFile, PublicKey), Box<dyn Error>> {
let key = PrivateKey::random(&mut OsRng, Algorithm::Ed25519)?;
let mut f = NamedTempFile::new()?;
f.write_all(key.to_openssh(Default::default())?.as_bytes())?;
Ok((f, key.public_key().clone()))
}
pub async fn setup() -> Result<(TestContext, Configuration), Box<dyn Error>> {
INIT.call_once(|| {
tracing_subscriber::fmt::fmt()
.with_env_filter(EnvFilter::from("sshca=trace"))
.with_test_writer()
.init();
});
let machine_ids = gen_machine_ids()?;
let (host_key, host_key_pub) = gen_ca_key()?;
let config = gen_config(machine_ids.path(), host_key.path());
let ctx = TestContext {
machine_ids,
host_key,
host_key_pub,
};
Ok((ctx, config))
}
#[allow(dead_code)]
pub struct TestContext {
machine_ids: NamedTempFile,
host_key: NamedTempFile,
host_key_pub: PublicKey,
}
impl TestContext {
pub fn host_ca_fingerprint(&self) -> Fingerprint {
self.host_key_pub.fingerprint(Default::default())
}
}

41
tests/common/token.rs Normal file
View File

@@ -0,0 +1,41 @@
use std::time;
use argon2::Argon2;
use jsonwebtoken::{encode, EncodingKey};
use serde::Serialize;
use uuid::Uuid;
#[derive(Debug, Serialize)]
struct TestClaims {
sub: String,
iss: String,
aud: String,
iat: u64,
nbf: u64,
exp: u64,
}
pub fn make_token(hostname: &str, machine_id: Uuid) -> String {
let now = time::SystemTime::now()
.duration_since(time::UNIX_EPOCH)
.unwrap()
.as_secs();
let claims = TestClaims {
sub: hostname.into(),
iss: hostname.into(),
aud: "sshca.example.org".into(),
nbf: now - 60,
iat: now,
exp: now + 60,
};
let mut secret = [0u8; 32];
Argon2::default()
.hash_password_into(
machine_id.as_bytes(),
hostname.as_bytes(),
&mut secret,
)
.unwrap();
let key = EncodingKey::from_secret(&secret);
encode(&Default::default(), &claims, &key).unwrap()
}