use hmac::{Hmac, Mac};
use sha2::{Digest as _, Sha256};
use sha3::Sha3_256;
#[derive(Clone, zeroize::ZeroizeOnDrop)]
pub struct ChainKey {
#[zeroize(skip)]
id: String,
secret: Vec<u8>,
}
impl std::fmt::Debug for ChainKey {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ChainKey")
.field("id", &self.id)
.field("secret", &"<redacted>")
.finish()
}
}
impl ChainKey {
pub fn from_hex(id: &str, hex: &str) -> Result<Self, String> {
let hex = hex.trim();
if !hex.len().is_multiple_of(2) {
return Err("chain key must be hex (even number of digits)".into());
}
let secret: Result<Vec<u8>, _> = (0..hex.len())
.step_by(2)
.map(|i| u8::from_str_radix(&hex[i..i + 2], 16))
.collect();
let secret = secret.map_err(|_| "chain key is not valid hex".to_string())?;
if secret.len() < 32 {
return Err(format!(
"chain key is {} bytes; at least 32 are required",
secret.len()
));
}
if id.is_empty() {
return Err("chain key id must not be empty".into());
}
Ok(Self {
id: id.to_string(),
secret,
})
}
pub fn from_file(id: &str, path: &std::path::Path) -> Result<Self, String> {
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt as _;
let meta = std::fs::metadata(path)
.map_err(|e| format!("chain key {}: {e}", path.display()))?;
let mode = meta.permissions().mode() & 0o077;
if mode != 0 {
return Err(format!(
"chain key {} is readable by group or other (mode {:o}); \
chmod 600 it",
path.display(),
meta.permissions().mode() & 0o777
));
}
}
let hex = std::fs::read_to_string(path)
.map_err(|e| format!("chain key {}: {e}", path.display()))?;
Self::from_hex(id, &hex)
}
pub fn generate_to_file(id: &str, path: &std::path::Path) -> Result<Self, String> {
use std::io::Write as _;
let mut secret = [0u8; 32];
getrandom::fill(&mut secret).map_err(|e| format!("no entropy available: {e}"))?;
let hex: String = secret.iter().map(|b| format!("{b:02x}")).collect();
let mut opts = std::fs::OpenOptions::new();
opts.write(true).create_new(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt as _;
opts.mode(0o600);
}
let mut f = opts
.open(path)
.map_err(|e| format!("chain key {}: {e}", path.display()))?;
writeln!(f, "{hex}").map_err(|e| format!("chain key {}: {e}", path.display()))?;
Self::from_hex(id, &hex)
}
pub fn from_env(prefix: &str) -> Result<Option<Self>, String> {
let Ok(hex) = std::env::var(format!("{prefix}_CHAIN_KEY")) else {
return Ok(None);
};
let id =
std::env::var(format!("{prefix}_CHAIN_KEY_ID")).unwrap_or_else(|_| "k1".to_string());
Self::from_hex(&id, &hex).map(Some)
}
#[must_use]
pub fn id(&self) -> &str {
&self.id
}
}
pub const GENESIS: [u8; 32] = [0u8; 32];
pub const ALGORITHMS: [&str; 2] = ["sha256", "sha3-256"];
#[must_use]
pub fn preimage(
id: &str,
version_id: i64,
last_updated: &str,
op: &str,
resource: Option<&str>,
actor: &str,
) -> Vec<u8> {
format!(
"{id}|{version_id}|{last_updated}|{op}|{}|{actor}",
resource.unwrap_or("")
)
.into_bytes()
}
#[must_use]
pub fn link(
prev_sha256: Option<&[u8]>,
prev_sha3: Option<&[u8]>,
preimage: &[u8],
) -> (Vec<u8>, Vec<u8>) {
let mut a = Sha256::new();
a.update(prev_sha256.unwrap_or(&GENESIS));
a.update(preimage);
let mut b = Sha3_256::new();
b.update(prev_sha3.unwrap_or(&GENESIS));
b.update(preimage);
(a.finalize().to_vec(), b.finalize().to_vec())
}
#[must_use]
pub fn mac(key: &ChainKey, prev_sha256: Option<&[u8]>, preimage: &[u8]) -> String {
let mut m =
<Hmac<Sha256> as Mac>::new_from_slice(&key.secret).expect("HMAC accepts any key length");
m.update(prev_sha256.unwrap_or(&GENESIS));
m.update(preimage);
let tag = m.finalize().into_bytes();
let hex: String = tag.iter().map(|b| format!("{b:02x}")).collect();
format!("{}:{hex}", key.id)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MacCheck {
Ok,
Mismatch,
Absent,
Unverifiable { key_id: String },
Malformed,
}
#[derive(Clone, Debug, Default)]
pub struct KeyRing {
keys: Vec<ChainKey>,
}
impl KeyRing {
#[must_use]
pub fn new(keys: Vec<ChainKey>) -> Self {
Self { keys }
}
pub fn from_files(
signing: Option<(&str, &std::path::Path)>,
retired: &[(String, std::path::PathBuf)],
) -> Result<Self, String> {
let mut keys = Vec::new();
if let Some((id, path)) = signing {
keys.push(ChainKey::from_file(id, path)?);
}
for (id, path) in retired {
keys.push(ChainKey::from_file(id, path)?);
}
Ok(Self { keys })
}
pub fn from_env(prefix: &str) -> Result<Self, String> {
let mut keys = Vec::new();
if let Some(k) = ChainKey::from_env(prefix)? {
keys.push(k);
}
if let Ok(retired) = std::env::var(format!("{prefix}_CHAIN_KEYS_RETIRED")) {
for entry in retired.split(',').map(str::trim).filter(|e| !e.is_empty()) {
let (id, hex) = entry
.split_once('=')
.ok_or_else(|| format!("retired key {entry:?} is not id=hex"))?;
keys.push(ChainKey::from_hex(id, hex)?);
}
}
Ok(Self { keys })
}
#[must_use]
pub fn signing(&self) -> Option<&ChainKey> {
self.keys.first()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.keys.is_empty()
}
#[must_use]
pub fn check(&self, stored: Option<&str>, prev_sha256: Option<&[u8]>, pre: &[u8]) -> MacCheck {
let Some(stored) = stored else {
return MacCheck::Absent;
};
let Some((id, _)) = stored.split_once(':') else {
return MacCheck::Malformed;
};
let Some(key) = self.keys.iter().find(|k| k.id == id) else {
return MacCheck::Unverifiable {
key_id: id.to_string(),
};
};
let expect = mac(key, prev_sha256, pre);
if digests_equal(stored.as_bytes(), expect.as_bytes()) {
MacCheck::Ok
} else {
MacCheck::Mismatch
}
}
}
#[must_use]
pub fn digests_equal(a: &[u8], b: &[u8]) -> bool {
use subtle::ConstantTimeEq as _;
a.ct_eq(b).into()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_two_algorithms_disagree_on_the_same_input() {
let (a, b) = link(None, None, b"x");
assert_ne!(a, b, "two families must not produce one digest");
assert_eq!(a.len(), 32);
assert_eq!(b.len(), 32);
}
#[test]
fn a_changed_preimage_changes_both() {
let (a1, b1) = link(None, None, &preimage("p", 1, "t", "C", Some("{}"), "who"));
let (a2, b2) = link(None, None, &preimage("p", 1, "t", "C", Some("{}"), "other"));
assert_ne!(a1, a2, "sha256 must notice the actor");
assert_ne!(b1, b2, "sha3 must notice the actor");
}
#[test]
fn a_changed_predecessor_changes_both() {
let pre = preimage("p", 2, "t", "U", Some("{}"), "who");
let (a1, b1) = link(Some(&[1u8; 32]), Some(&[1u8; 32]), &pre);
let (a2, b2) = link(Some(&[2u8; 32]), Some(&[2u8; 32]), &pre);
assert_ne!(a1, a2);
assert_ne!(b1, b2);
}
#[test]
fn genesis_is_thirty_two_zero_bytes() {
assert_eq!(GENESIS.len(), 32);
assert_eq!(
link(None, None, b"x"),
link(Some(&GENESIS), Some(&GENESIS), b"x")
);
}
fn key() -> ChainKey {
ChainKey::from_hex("kt", &"ab".repeat(32)).expect("test key")
}
#[test]
fn digests_are_reproducible_but_the_mac_is_not() {
let pre = preimage("p", 1, "t", "C", Some("{}"), "who");
assert_eq!(link(None, None, &pre), link(None, None, &pre));
let real = mac(&key(), None, &pre);
for guess in ["changeme", "00", "secret"] {
if let Ok(k) = ChainKey::from_hex("kt", &"00".repeat(32)) {
assert_ne!(mac(&k, None, &pre), real, "guessed key {guess} matched");
}
}
assert!(real.starts_with("kt:"), "the tag names its key: {real}");
}
#[test]
fn absent_unverifiable_and_malformed_are_not_findings() {
let pre = preimage("p", 1, "t", "C", Some("{}"), "who");
let ring = KeyRing { keys: vec![key()] };
assert_eq!(ring.check(None, None, &pre), MacCheck::Absent);
assert_eq!(
ring.check(Some("k9:abcd"), None, &pre),
MacCheck::Unverifiable {
key_id: "k9".into()
}
);
assert_eq!(
ring.check(Some("no-colon"), None, &pre),
MacCheck::Malformed
);
assert_eq!(
ring.check(Some(&mac(&key(), None, &pre)), None, &pre),
MacCheck::Ok
);
assert_eq!(
ring.check(Some("kt:00"), None, &pre),
MacCheck::Mismatch,
"a wrong tag under a key we hold is the one real finding"
);
}
#[test]
fn a_retired_key_still_verifies_its_rows() {
let old = ChainKey::from_hex("k1", &"11".repeat(32)).expect("key");
let new = ChainKey::from_hex("k2", &"22".repeat(32)).expect("key");
let pre = preimage("p", 1, "t", "C", Some("{}"), "who");
let signed_with_old = mac(&old, None, &pre);
let ring = KeyRing {
keys: vec![new, old],
};
assert_eq!(ring.signing().map(ChainKey::id), Some("k2"), "newest signs");
assert_eq!(ring.check(Some(&signed_with_old), None, &pre), MacCheck::Ok);
}
#[test]
fn a_different_key_yields_a_different_digest() {
let pre = preimage("p", 1, "t", "C", Some("{}"), "who");
let other = ChainKey::from_hex("kt", &"cd".repeat(32)).expect("key");
assert_ne!(mac(&key(), None, &pre), mac(&other, None, &pre));
}
#[test]
fn short_and_malformed_keys_are_refused() {
assert!(
ChainKey::from_hex("k", &"ab".repeat(16)).is_err(),
"16 bytes is too short"
);
assert!(ChainKey::from_hex("k", "not-hex").is_err());
assert!(
ChainKey::from_hex("", &"ab".repeat(32)).is_err(),
"id is required"
);
assert!(ChainKey::from_hex("k", &"ab".repeat(32)).is_ok());
}
#[test]
fn debug_never_renders_the_secret() {
let rendered = format!("{:?}", key());
assert!(!rendered.contains("abab"), "secret leaked: {rendered}");
assert!(rendered.contains("redacted"));
assert!(rendered.contains("kt"), "the id is safe and useful to show");
}
#[test]
fn digest_comparison_is_available_and_correct() {
assert!(digests_equal(&[1, 2, 3], &[1, 2, 3]));
assert!(!digests_equal(&[1, 2, 3], &[1, 2, 4]));
assert!(!digests_equal(&[1, 2, 3], &[1, 2]));
}
#[test]
#[cfg(unix)]
fn a_group_readable_key_file_is_refused() {
use std::io::Write as _;
use std::os::unix::fs::PermissionsExt as _;
let dir = std::env::temp_dir().join(format!("fhir-sqlite-keytest-{}", std::process::id()));
std::fs::create_dir_all(&dir).expect("dir");
let path = dir.join("chain.key");
let mut f = std::fs::File::create(&path).expect("create");
f.write_all(&b"ab".repeat(32)).expect("write");
drop(f);
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o640)).expect("chmod");
let err = ChainKey::from_file("k", &path).expect_err("0640 must be refused");
assert!(err.contains("group or other"), "unhelpful message: {err}");
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).expect("chmod");
let key = ChainKey::from_file("k", &path).expect("0600 is fine");
assert_eq!(key.id(), "k");
std::fs::write(&path, format!("{}\n", "ab".repeat(32))).expect("write");
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).expect("chmod");
assert!(
ChainKey::from_file("k", &path).is_ok(),
"a trailing newline must not break a key file"
);
std::fs::remove_dir_all(&dir).ok();
}
#[test]
fn an_unreadable_retired_key_is_an_error() {
let missing = std::path::PathBuf::from("/nonexistent/fhir-sqlite/retired.key");
let err = KeyRing::from_files(None, &[("k1".to_string(), missing)])
.expect_err("must not silently skip");
assert!(err.contains("k1") || err.contains("retired.key"), "{err}");
}
#[test]
fn preimage_format_is_stable() {
assert_eq!(
preimage(
"p1",
3,
"2026-01-01 00:00:00+00",
"U",
Some("{\"a\": 1}"),
"clinician"
),
b"p1|3|2026-01-01 00:00:00+00|U|{\"a\": 1}|clinician".to_vec()
);
assert_eq!(
preimage("p1", 1, "t", "D", None, "who"),
b"p1|1|t|D||who".to_vec()
);
}
}