use ostrya_core::{Type, Value};
use crate::config::repo;
use crate::error::Result;
use crate::repo::Repo;
use crate::repo_fs::{FsError, FsResultExt, Publish, RepoDir, RepoLayout};
use crate::sign::{MAX_X509_CRL, MAX_X509_CRLS, Verifier, X509_CRLS_KEY, X509KeptCrl};
const CACHE_SUBDIR: &str = "ostrya/x509-crl";
const ISSUER_DIGITS: usize = 64;
const NUMBER_DIGITS: usize = 40;
fn hex_name(name: &[u8], digits: usize) -> Option<&str> {
(name.len() == digits && name.iter().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f')))
.then(|| std::str::from_utf8(name).ok())
.flatten()
}
fn highest(dir: &RepoDir) -> Result<Option<String>> {
Ok(dir
.list()?
.iter()
.filter_map(|entry| hex_name(&entry.name, NUMBER_DIGITS))
.max()
.map(str::to_owned))
}
pub(crate) fn cache_dirs<'a>(
verifiers: impl IntoIterator<Item = &'a dyn Verifier>,
dict: Option<&Value>,
) -> Vec<String> {
let mut dirs: Vec<String> = Vec::new();
for verifier in verifiers {
for dir in verifier.x509_crl_cache_dirs(dict) {
if !dirs.contains(&dir) {
dirs.push(dir);
}
}
}
dirs
}
pub(crate) fn read(root: &RepoDir, dirs: &[String]) -> Result<Vec<Vec<u8>>> {
let mut issuers: Vec<&str> = dirs
.iter()
.filter_map(|dir| hex_name(dir.as_bytes(), ISSUER_DIGITS))
.collect();
if issuers.is_empty() {
return Ok(Vec::new());
}
issuers.sort_unstable();
issuers.dedup();
let Some(extensions) = root.open_layout(RepoLayout::Extensions).optional()? else {
return Ok(Vec::new());
};
let Some(cache) = extensions.open_dir(CACHE_SUBDIR).optional()? else {
return Ok(Vec::new());
};
let mut crls = Vec::with_capacity(issuers.len());
for issuer in issuers {
let Some(dir) = cache.open_dir(issuer).optional()? else {
continue;
};
while let Some(number) = highest(&dir)? {
match dir.read_capped(&number, MAX_X509_CRL as u64) {
Ok(crl) => {
crls.push(crl);
break;
}
Err(FsError::Absent { .. }) => continue,
Err(err) => return Err(err.into()),
}
}
}
Ok(crls)
}
pub(crate) fn dicts(crls: Vec<Vec<u8>>) -> Vec<Value> {
let ty = Type::array(Type::array(Type::Byte));
let mut crls = crls.into_iter();
let mut dicts = Vec::new();
loop {
let chunk: Vec<Value> = crls
.by_ref()
.take(MAX_X509_CRLS)
.map(Value::Bytes)
.collect();
if chunk.is_empty() {
return dicts;
}
dicts.push(Value::Array(vec![Value::Tuple(vec![
Value::Str(X509_CRLS_KEY.to_owned()),
Value::variant(ty.clone(), Value::Array(chunk)),
])]));
}
}
fn existing_dir(root: &RepoDir, path: &str) -> Result<Option<RepoDir>> {
let Some(extensions) = root.open_layout(RepoLayout::Extensions).optional()? else {
return Ok(None);
};
Ok(extensions.open_dir(path).optional()?)
}
pub(crate) fn write(root: &RepoDir, crls: &[X509KeptCrl], fsync: bool) -> Result<()> {
for crl in crls {
let Some((issuer, number)) = ostrya_sign::x509_crl_cache_name(crl) else {
continue;
};
let path = format!("{CACHE_SUBDIR}/{issuer}");
let existing = existing_dir(root, &path)?;
if let Some(dir) = &existing
&& highest(dir)?.is_some_and(|held| held >= number)
{
continue;
}
if !ostrya_sign::x509_crl_usable(&crl.der) {
continue;
}
let dir = match existing {
Some(dir) => dir,
None => root
.ensure_layout(RepoLayout::Extensions, fsync)?
.ensure_dir(&path, fsync)?,
};
dir.write_atomic(&number, &crl.der, Publish::KeepExisting, fsync)?;
let lower: Vec<String> = dir
.list()?
.iter()
.filter_map(|entry| hex_name(&entry.name, NUMBER_DIGITS))
.filter(|name| *name < number.as_str())
.map(str::to_owned)
.collect();
for name in lower {
dir.remove_file(&name, fsync)?;
}
}
Ok(())
}
impl Repo {
pub async fn x509_crl_context(
&self,
verifiers: &[&dyn Verifier],
dict: Option<&Value>,
) -> Result<Vec<Value>> {
let dirs = cache_dirs(verifiers.iter().copied(), dict);
if dirs.is_empty() {
return Ok(Vec::new());
}
let repo = self.clone();
ostrya_rt::unblock(move || read(repo.root_dir(), &dirs).map(dicts)).await
}
pub async fn cache_x509_crls(&self, crls: &[X509KeptCrl]) -> Result<()> {
if crls.is_empty() {
return Ok(());
}
let fsync = self.config().get::<repo::Fsync>()?;
let repo = self.clone();
let crls = crls.to_vec();
ostrya_rt::unblock(move || write(repo.root_dir(), &crls, fsync)).await
}
}
#[cfg(test)]
mod tests {
use std::path::{Path, PathBuf};
use super::*;
use crate::{CreateOptions, RepoMode};
const SIGNER: &[u8] = b"the key of the intermediate";
const OTHER_SIGNER: &[u8] = b"the key of another intermediate";
fn fixture(name: &str) -> Vec<u8> {
let path = Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../../tests/fixtures/x509")
.join(name);
crate::spki::x509_crls(&std::fs::read(path).unwrap(), name)
.unwrap()
.remove(0)
}
fn kept(name: &str, signer: &[u8]) -> X509KeptCrl {
X509KeptCrl {
der: fixture(name),
signer: signer.to_vec(),
}
}
fn numbered(signer: &[u8]) -> [X509KeptCrl; 3] {
[
kept("intermediate.crl.pem", signer),
kept("intermediate-2.crl.pem", signer),
kept("intermediate-stale.crl.pem", signer),
]
}
fn dir_of(crl: &X509KeptCrl) -> String {
ostrya_sign::x509_crl_cache_name(crl).unwrap().0
}
fn number_of(crl: &X509KeptCrl) -> String {
ostrya_sign::x509_crl_cache_name(crl).unwrap().1
}
struct Scratch {
dir: PathBuf,
repo: Repo,
}
impl Scratch {
fn new(name: &str) -> Scratch {
let dir = std::env::temp_dir().join(format!(
"ostrya-crl-cache-{name}-{}-{}",
std::process::id(),
crate::write::unique()
));
std::fs::create_dir_all(&dir).unwrap();
let repo = ostrya_rt::block_on(Repo::create(
&dir.join("repo"),
CreateOptions::new(RepoMode::Archive),
))
.unwrap();
Scratch { dir, repo }
}
fn cache(&self) -> PathBuf {
self.dir.join("repo/extensions").join(CACHE_SUBDIR)
}
fn issuer_dir(&self, crl: &X509KeptCrl) -> PathBuf {
self.cache().join(dir_of(crl))
}
fn names(&self, crl: &X509KeptCrl) -> Vec<String> {
let mut names: Vec<String> = std::fs::read_dir(self.issuer_dir(crl))
.unwrap()
.map(|e| e.unwrap().file_name().into_string().unwrap())
.collect();
names.sort();
names
}
fn write(&self, crls: &[X509KeptCrl]) {
write(self.repo.root_dir(), crls, false).unwrap();
}
fn read(&self, crls: &[&X509KeptCrl]) -> Result<Vec<Vec<u8>>> {
let dirs: Vec<String> = crls.iter().map(|crl| dir_of(crl)).collect();
read(self.repo.root_dir(), &dirs)
}
}
impl Drop for Scratch {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.dir);
}
}
#[test]
fn the_cache_keeps_the_highest_number_of_each_issuer() {
let scratch = Scratch::new("highest");
let [one, two, _] = numbered(SIGNER);
let root = kept("root.crl.pem", b"the key of the root");
assert!(scratch.read(&[&one, &root]).unwrap().is_empty());
scratch.write(std::slice::from_ref(&one));
scratch.write(&[two.clone(), root.clone()]);
assert_eq!(scratch.names(&two), [number_of(&two)]);
scratch.write(std::slice::from_ref(&one));
assert_eq!(scratch.names(&two), [number_of(&two)]);
let mut held = scratch.read(&[&two, &root]).unwrap();
held.sort();
let mut expected = vec![two.der.clone(), root.der.clone()];
expected.sort();
assert_eq!(held, expected);
assert_eq!(dicts(held).len(), 1);
assert_eq!(scratch.read(&[&root]).unwrap(), [root.der]);
assert!(read(scratch.repo.root_dir(), &[]).unwrap().is_empty());
}
#[test]
fn a_crl_of_another_signer_with_the_same_issuer_name_evicts_and_blocks_nothing() {
let scratch = Scratch::new("signers");
let [one, two, _] = numbered(SIGNER);
let [_, _, foreign] = numbered(OTHER_SIGNER);
scratch.write(std::slice::from_ref(&one));
scratch.write(std::slice::from_ref(&foreign));
assert_ne!(dir_of(&one), dir_of(&foreign));
assert_eq!(scratch.names(&one), [number_of(&one)]);
assert_eq!(
scratch.read(&[&one]).unwrap(),
std::slice::from_ref(&one.der)
);
scratch.write(std::slice::from_ref(&two));
assert_eq!(scratch.names(&two), [number_of(&two)]);
assert_eq!(scratch.names(&foreign), [number_of(&foreign)]);
assert_eq!(scratch.read(&[&two]).unwrap(), [two.der]);
assert_eq!(scratch.read(&[&foreign]).unwrap(), [foreign.der]);
}
#[test]
fn a_writer_with_a_lower_number_removes_nothing_above_it() {
let scratch = Scratch::new("lower");
let [one, two, three] = numbered(SIGNER);
scratch.write(std::slice::from_ref(&one));
std::fs::write(scratch.issuer_dir(&one).join(number_of(&three)), &three.der).unwrap();
scratch.write(std::slice::from_ref(&two));
assert_eq!(scratch.names(&one), [number_of(&one), number_of(&three)]);
assert_eq!(scratch.read(&[&one]).unwrap(), [three.der]);
}
#[test]
fn two_writers_at_once_keep_the_highest_number() {
let crls = numbered(SIGNER);
for round in 0..16 {
let scratch = Scratch::new("race");
let path = scratch.dir.join("repo");
let other = if round % 2 == 1 {
ostrya_rt::block_on(Repo::open(&path)).unwrap()
} else {
scratch.repo.clone()
};
let mut order = [0usize, 1, 2];
order.rotate_left(round % 3);
if round % 4 >= 2 {
order.reverse();
}
std::thread::scope(|s| {
for (n, index) in order.into_iter().enumerate() {
let repo = if n % 2 == 0 { &scratch.repo } else { &other };
let crl = &crls[index];
s.spawn(move || {
write(repo.root_dir(), std::slice::from_ref(crl), false).unwrap();
});
}
});
let names = scratch.names(&crls[2]);
assert_eq!(names.last(), Some(&number_of(&crls[2])), "{order:?}");
assert_eq!(scratch.read(&[&crls[2]]).unwrap(), [crls[2].der.clone()]);
}
}
#[test]
fn other_names_are_ignored_and_a_symlink_fails_the_read() {
let scratch = Scratch::new("names");
let [one, two, _] = numbered(SIGNER);
scratch.write(std::slice::from_ref(&one));
std::fs::write(scratch.cache().join("README"), b"x").unwrap();
std::fs::write(scratch.issuer_dir(&one).join("NOTES"), b"x").unwrap();
std::fs::write(
scratch
.issuer_dir(&one)
.join(number_of(&one).to_uppercase() + "f"),
b"x",
)
.unwrap();
let dirs = [dir_of(&one), "README".to_owned(), "../x".to_owned()];
assert_eq!(
read(scratch.repo.root_dir(), &dirs).unwrap(),
std::slice::from_ref(&one.der)
);
std::os::unix::fs::symlink(
number_of(&one),
scratch.issuer_dir(&one).join(number_of(&two)),
)
.unwrap();
let err = scratch.read(&[&one]).unwrap_err();
assert!(
matches!(&err, crate::Error::InvalidFormat(m) if m.contains("symlink")),
"{err:?}"
);
}
#[test]
fn a_crl_that_the_check_does_not_use_is_not_written() {
let scratch = Scratch::new("unused");
scratch.write(&[kept("crl-no-number.pem", SIGNER)]);
assert!(!scratch.cache().exists());
}
#[test]
fn the_cache_is_given_in_dicts_of_at_most_16_crls() {
let crl = fixture("intermediate.crl.pem");
let held = dicts(vec![crl.clone(); MAX_X509_CRLS + 1]);
assert_eq!(held.len(), 2);
assert_eq!(ostrya_sign::x509_crls_in(&held[0]).len(), MAX_X509_CRLS);
assert_eq!(ostrya_sign::x509_crls_in(&held[1]), [&crl[..]]);
assert!(dicts(Vec::new()).is_empty());
}
}