Compare commits
12 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| ac69cf4638 | |||
| 65c87186d6 | |||
| 7f90f952f0 | |||
| 12a5ba31d8 | |||
| 8a10c695c5 | |||
| 6739423f4d | |||
| 8660b887c1 | |||
| 23a8878f32 | |||
| 37634f0d26 | |||
| 76a94b0d11 | |||
| 4e386e8113 | |||
| 92ab8a0d63 |
Generated
+12
-10
@@ -329,7 +329,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "custos-gen"
|
name = "custos-gen"
|
||||||
version = "0.9.0"
|
version = "0.12.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"custos-vault",
|
"custos-vault",
|
||||||
"data-encoding",
|
"data-encoding",
|
||||||
@@ -341,7 +341,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "custos-kdbx"
|
name = "custos-kdbx"
|
||||||
version = "0.9.0"
|
version = "0.12.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"aes",
|
"aes",
|
||||||
"argon2",
|
"argon2",
|
||||||
@@ -362,7 +362,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "custos-keys"
|
name = "custos-keys"
|
||||||
version = "0.9.0"
|
version = "0.12.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"custos-vault",
|
"custos-vault",
|
||||||
"ed25519-dalek",
|
"ed25519-dalek",
|
||||||
@@ -375,11 +375,11 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "custos-qr"
|
name = "custos-qr"
|
||||||
version = "0.9.0"
|
version = "0.12.0"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "custos-seal"
|
name = "custos-seal"
|
||||||
version = "0.9.0"
|
version = "0.12.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"chacha20poly1305",
|
"chacha20poly1305",
|
||||||
"hkdf",
|
"hkdf",
|
||||||
@@ -392,7 +392,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "custos-share"
|
name = "custos-share"
|
||||||
version = "0.9.0"
|
version = "0.12.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"argon2",
|
"argon2",
|
||||||
"chacha20poly1305",
|
"chacha20poly1305",
|
||||||
@@ -409,7 +409,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "custos-sign"
|
name = "custos-sign"
|
||||||
version = "0.9.0"
|
version = "0.12.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"blake2 0.10.6",
|
"blake2 0.10.6",
|
||||||
"data-encoding",
|
"data-encoding",
|
||||||
@@ -418,6 +418,8 @@ dependencies = [
|
|||||||
"rand 0.10.3",
|
"rand 0.10.3",
|
||||||
"rand_core 0.6.4",
|
"rand_core 0.6.4",
|
||||||
"rsa",
|
"rsa",
|
||||||
|
"serde",
|
||||||
|
"serde_json",
|
||||||
"sha2 0.10.9",
|
"sha2 0.10.9",
|
||||||
"thiserror",
|
"thiserror",
|
||||||
"x509-cert",
|
"x509-cert",
|
||||||
@@ -426,7 +428,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "custos-totp"
|
name = "custos-totp"
|
||||||
version = "0.9.0"
|
version = "0.12.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"custos-vault",
|
"custos-vault",
|
||||||
"data-encoding",
|
"data-encoding",
|
||||||
@@ -439,7 +441,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "custos-vault"
|
name = "custos-vault"
|
||||||
version = "0.9.0"
|
version = "0.12.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"argon2",
|
"argon2",
|
||||||
"bip39",
|
"bip39",
|
||||||
@@ -463,7 +465,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "custos-wasm"
|
name = "custos-wasm"
|
||||||
version = "0.9.0"
|
version = "0.12.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"custos-qr",
|
"custos-qr",
|
||||||
"custos-seal",
|
"custos-seal",
|
||||||
|
|||||||
+1
-1
@@ -3,7 +3,7 @@ resolver = "3"
|
|||||||
members = ["crates/*"]
|
members = ["crates/*"]
|
||||||
|
|
||||||
[workspace.package]
|
[workspace.package]
|
||||||
version = "0.9.0"
|
version = "0.12.0"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
license = "MPL-2.0"
|
license = "MPL-2.0"
|
||||||
repository = "https://gitea.marek-novak.cz/mnovak/CustosPublic"
|
repository = "https://gitea.marek-novak.cz/mnovak/CustosPublic"
|
||||||
|
|||||||
@@ -52,7 +52,9 @@ fn random<const N: usize>() -> Zeroizing<[u8; N]> {
|
|||||||
|
|
||||||
fn derive(ikm: &[u8], salt: &[u8], info: &[&[u8]]) -> Zeroizing<[u8; 32]> {
|
fn derive(ikm: &[u8], salt: &[u8], info: &[&[u8]]) -> Zeroizing<[u8; 32]> {
|
||||||
let mut k = Zeroizing::new([0u8; 32]);
|
let mut k = Zeroizing::new([0u8; 32]);
|
||||||
hkdf::Hkdf::<Sha256>::new(Some(salt), ikm).expand(&info.concat(), k.as_mut()).expect("32 bytes is a valid HKDF length");
|
hkdf::Hkdf::<Sha256>::new(Some(salt), ikm)
|
||||||
|
.expand(&info.concat(), k.as_mut())
|
||||||
|
.expect("32 bytes is a valid HKDF length");
|
||||||
k
|
k
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -64,8 +66,8 @@ fn xnonce(n: &[u8]) -> XNonce {
|
|||||||
XNonce::try_from(n).expect("24-byte nonce")
|
XNonce::try_from(n).expect("24-byte nonce")
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The one-time key pair of a device waiting for a secret. Its secret half never leaves memory and is
|
/// The one-time key pair of a device waiting for a secret. Its secret half is wiped on drop and leaves
|
||||||
/// wiped on drop.
|
/// memory only through `secret_bytes`, for a caller that keeps a long-lived key (`from_secret`).
|
||||||
pub struct Recipient {
|
pub struct Recipient {
|
||||||
secret: StaticSecret,
|
secret: StaticSecret,
|
||||||
public: [u8; 32],
|
public: [u8; 32],
|
||||||
@@ -78,6 +80,30 @@ impl Recipient {
|
|||||||
Recipient { secret, public }
|
Recipient { secret, public }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A long-lived key the caller kept (docs/SEAL.md, "A kept key"): the PC's Provisio sealing key, stored
|
||||||
|
/// DPAPI-sealed and restored at start. Refuses a secret everyone knows: one that clamps to zero (a
|
||||||
|
/// wiped or never-filled buffer), and, as `seal` does for a public key, one whose shared secrets would
|
||||||
|
/// not be contributory.
|
||||||
|
pub fn from_secret(secret: Zeroizing<[u8; 32]>) -> Result<Recipient, SealError> {
|
||||||
|
let secret = StaticSecret::from(*secret);
|
||||||
|
let public = PublicKey::from(&secret).to_bytes();
|
||||||
|
let zero = PublicKey::from(&StaticSecret::from([0u8; 32])).to_bytes();
|
||||||
|
if public == zero {
|
||||||
|
return Err(SealError::BadKey);
|
||||||
|
}
|
||||||
|
let probe = StaticSecret::from(*random::<32>());
|
||||||
|
if !probe.diffie_hellman(&PublicKey::from(public)).was_contributory() {
|
||||||
|
return Err(SealError::BadKey);
|
||||||
|
}
|
||||||
|
Ok(Recipient { secret, public })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The secret half, for a caller that keeps this key (sealed with DPAPI or the like) instead of
|
||||||
|
/// dropping it after one box. One-time keys never call this.
|
||||||
|
pub fn secret_bytes(&self) -> Zeroizing<[u8; 32]> {
|
||||||
|
Zeroizing::new(self.secret.to_bytes())
|
||||||
|
}
|
||||||
|
|
||||||
/// What the device sends: 32 bytes.
|
/// What the device sends: 32 bytes.
|
||||||
pub fn public(&self) -> [u8; 32] {
|
pub fn public(&self) -> [u8; 32] {
|
||||||
self.public
|
self.public
|
||||||
@@ -109,7 +135,7 @@ impl Recipient {
|
|||||||
|
|
||||||
impl std::fmt::Debug for Recipient {
|
impl std::fmt::Debug for Recipient {
|
||||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
write!(f, "Recipient {{ match_code: {} }}", self.match_code())
|
write!(f, "Recipient {{ match_code: {}, secret: [redacted] }}", self.match_code())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -72,3 +72,47 @@ fn at_rest_seals_open_with_the_same_key_and_context_only() {
|
|||||||
assert_eq!(open_at_rest(&key, b"totp:f2", &b), Err(SealError::Rejected));
|
assert_eq!(open_at_rest(&key, b"totp:f2", &b), Err(SealError::Rejected));
|
||||||
assert_eq!(open_at_rest(&key, b"totp:f1", b"CSR1"), Err(SealError::Malformed));
|
assert_eq!(open_at_rest(&key, b"totp:f1", b"CSR1"), Err(SealError::Malformed));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_kept_recipient_comes_back_from_its_secret() {
|
||||||
|
// The PC keeps its Provisio sealing key (DPAPI-sealed) and restores it at the next start.
|
||||||
|
let r = Recipient::generate();
|
||||||
|
let kept = r.secret_bytes();
|
||||||
|
let back = Recipient::from_secret(kept).unwrap();
|
||||||
|
assert_eq!(back.public(), r.public());
|
||||||
|
assert_eq!(back.match_code(), r.match_code());
|
||||||
|
assert_eq!(back.secret_bytes().as_slice(), r.secret_bytes().as_slice());
|
||||||
|
// A box sealed to the original opens with the restored key, for its purpose only.
|
||||||
|
let ctx = b"provision-offer:vault:fabrica/gitea-read-token";
|
||||||
|
let b = seal(&r.public(), ctx, b"gitea token").unwrap();
|
||||||
|
assert_eq!(back.open(&b, ctx).unwrap().as_slice(), b"gitea token");
|
||||||
|
assert_eq!(back.open(&b, b"provision-offer:vault:fabrica/other"), Err(SealError::Rejected));
|
||||||
|
// Another kept key does not open it.
|
||||||
|
let other = Recipient::from_secret(Recipient::generate().secret_bytes()).unwrap();
|
||||||
|
assert_eq!(other.open(&b, ctx), Err(SealError::Rejected));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_known_secret_is_refused() {
|
||||||
|
// All zeros (a wiped or never-filled buffer) is a key everyone knows, and so is anything that clamps to it.
|
||||||
|
assert_eq!(Recipient::from_secret(zeroize::Zeroizing::new([0u8; 32])).unwrap_err(), SealError::BadKey);
|
||||||
|
let mut clamps_to_zero = [0u8; 32];
|
||||||
|
clamps_to_zero[0] = 0b0000_0111;
|
||||||
|
clamps_to_zero[31] = 0b1000_0000;
|
||||||
|
assert_eq!(Recipient::from_secret(zeroize::Zeroizing::new(clamps_to_zero)).unwrap_err(), SealError::BadKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_kept_recipient_prints_redacted() {
|
||||||
|
let r = Recipient::generate();
|
||||||
|
let secret = r.secret_bytes();
|
||||||
|
let back = Recipient::from_secret(secret.clone()).unwrap();
|
||||||
|
for shown in [format!("{r:?}"), format!("{back:?}"), format!("{back:#?}")] {
|
||||||
|
assert!(shown.contains("[redacted]"), "{shown}");
|
||||||
|
assert!(!shown.contains(&format!("{:?}", *secret)));
|
||||||
|
assert!(!shown.contains(&format!("{:?}", &secret[..8])));
|
||||||
|
let hex: String = secret.iter().map(|b| format!("{b:02x}")).collect();
|
||||||
|
assert!(!shown.contains(&hex[..16]));
|
||||||
|
assert!(!shown.contains(&format!("{:?}", back.public())));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -10,6 +10,9 @@ repository.workspace = true
|
|||||||
thiserror.workspace = true
|
thiserror.workspace = true
|
||||||
zeroize.workspace = true
|
zeroize.workspace = true
|
||||||
data-encoding.workspace = true
|
data-encoding.workspace = true
|
||||||
|
# Deploy approvals: parsed, then written again in canonical form and compared.
|
||||||
|
serde.workspace = true
|
||||||
|
serde_json.workspace = true
|
||||||
# The RustCrypto generation custos-keys already uses (digest 0.10, signature 2).
|
# The RustCrypto generation custos-keys already uses (digest 0.10, signature 2).
|
||||||
ed25519-dalek = "2"
|
ed25519-dalek = "2"
|
||||||
rsa = { version = "0.9", default-features = false, features = ["sha2", "u64_digit"] }
|
rsa = { version = "0.9", default-features = false, features = ["sha2", "u64_digit"] }
|
||||||
|
|||||||
@@ -52,6 +52,8 @@ pub enum Error {
|
|||||||
BadKey,
|
BadKey,
|
||||||
#[error("the certificate cannot be built or read")]
|
#[error("the certificate cannot be built or read")]
|
||||||
Certificate,
|
Certificate,
|
||||||
|
#[error("the approval cannot be signed: {0}")]
|
||||||
|
Approval(&'static str),
|
||||||
}
|
}
|
||||||
|
|
||||||
/// An Ed25519 seed. Wiped on drop; never printed.
|
/// An Ed25519 seed. Wiped on drop; never printed.
|
||||||
@@ -360,3 +362,180 @@ pub fn cert_pem(der: &[u8]) -> String {
|
|||||||
pub fn sha256_hex(bytes: &[u8]) -> String {
|
pub fn sha256_hex(bytes: &[u8]) -> String {
|
||||||
Sha256::digest(bytes).iter().map(|b| format!("{b:02x}")).collect()
|
Sha256::digest(bytes).iter().map(|b| format!("{b:02x}")).collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ---- deploy approvals ----
|
||||||
|
|
||||||
|
/// The largest approval text Custos reads (docs/SIGNING.md).
|
||||||
|
pub const MAX_APPROVAL: usize = 8 * 1024;
|
||||||
|
/// An approval expires at most this many seconds after it is checked.
|
||||||
|
pub const APPROVAL_MAX_AHEAD: u64 = 3600;
|
||||||
|
|
||||||
|
/// A deploy approval, read from its canonical JSON (docs/SIGNING.md, "approval"). Nothing in it is secret.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
pub struct Approval {
|
||||||
|
pub run: String,
|
||||||
|
pub repo: String,
|
||||||
|
pub commit: String,
|
||||||
|
pub pipeline: String,
|
||||||
|
pub version: String,
|
||||||
|
pub targets: Vec<String>,
|
||||||
|
/// Unix seconds.
|
||||||
|
pub expires: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The JSON as it is parsed: `v` first, the rest as [`Approval`].
|
||||||
|
#[derive(serde::Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
struct ApprovalJson {
|
||||||
|
v: u64,
|
||||||
|
run: String,
|
||||||
|
repo: String,
|
||||||
|
commit: String,
|
||||||
|
pipeline: String,
|
||||||
|
version: String,
|
||||||
|
targets: Vec<String>,
|
||||||
|
expires: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Approval {
|
||||||
|
/// The canonical text (docs/SIGNING.md): one line, no spaces, keys in the fixed order, `"` and `\` escaped,
|
||||||
|
/// nothing else. Meaningful for an approval that passed [`approval_check`].
|
||||||
|
pub fn canonical(&self) -> String {
|
||||||
|
fn string(out: &mut String, s: &str) {
|
||||||
|
out.push('"');
|
||||||
|
for c in s.chars() {
|
||||||
|
match c {
|
||||||
|
'"' => out.push_str("\\\""),
|
||||||
|
'\\' => out.push_str("\\\\"),
|
||||||
|
c => out.push(c),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out.push('"');
|
||||||
|
}
|
||||||
|
let mut out = String::with_capacity(256);
|
||||||
|
out.push_str("{\"v\":1,\"run\":");
|
||||||
|
string(&mut out, &self.run);
|
||||||
|
out.push_str(",\"repo\":");
|
||||||
|
string(&mut out, &self.repo);
|
||||||
|
out.push_str(",\"commit\":");
|
||||||
|
string(&mut out, &self.commit);
|
||||||
|
out.push_str(",\"pipeline\":");
|
||||||
|
string(&mut out, &self.pipeline);
|
||||||
|
out.push_str(",\"version\":");
|
||||||
|
string(&mut out, &self.version);
|
||||||
|
out.push_str(",\"targets\":[");
|
||||||
|
for (i, t) in self.targets.iter().enumerate() {
|
||||||
|
if i > 0 {
|
||||||
|
out.push(',');
|
||||||
|
}
|
||||||
|
string(&mut out, t);
|
||||||
|
}
|
||||||
|
out.push_str("],\"expires\":");
|
||||||
|
out.push_str(&self.expires.to_string());
|
||||||
|
out.push('}');
|
||||||
|
out
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A run id: `[A-Za-z0-9._-]{1,64}`.
|
||||||
|
pub fn run_id_ok(run: &str) -> bool {
|
||||||
|
(1..=64).contains(&run.len()) && run.bytes().all(|c| c.is_ascii_alphanumeric() || b"._-".contains(&c))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `[A-Za-z0-9._+-]{1,64}`: an approval's repo, pipeline and version.
|
||||||
|
fn name_ok(s: &str) -> bool {
|
||||||
|
(1..=64).contains(&s.len()) && s.bytes().all(|c| c.is_ascii_alphanumeric() || b"._+-".contains(&c))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Characters a target may not hold: control characters, and the invisible ones that change how the rest of the
|
||||||
|
/// line is shown on the card (bidi overrides and isolates, zero-width characters, line separators, soft hyphen).
|
||||||
|
fn unprintable(c: char) -> bool {
|
||||||
|
c.is_control()
|
||||||
|
|| matches!(c, '\u{00AD}' | '\u{061C}' | '\u{180E}' | '\u{200B}'..='\u{200F}' | '\u{2028}'..='\u{202E}')
|
||||||
|
|| matches!(c, '\u{2060}'..='\u{2069}' | '\u{FEFF}')
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Checks that `text` is a deploy approval in canonical form that has not expired at `now_secs` and expires at most
|
||||||
|
/// an hour later (docs/SIGNING.md). It is parsed, written again in canonical form and compared byte for byte, so
|
||||||
|
/// any other spelling of the same values (key order, spaces, escapes, a trailing newline) is refused.
|
||||||
|
pub fn approval_check(text: &str, now_secs: u64) -> Result<Approval, Error> {
|
||||||
|
let a = approval_parse(text)?;
|
||||||
|
if a.expires <= now_secs {
|
||||||
|
return Err(Error::Approval("it has expired"));
|
||||||
|
}
|
||||||
|
if a.expires > now_secs.saturating_add(APPROVAL_MAX_AHEAD) {
|
||||||
|
return Err(Error::Approval("it expires more than an hour from now"));
|
||||||
|
}
|
||||||
|
Ok(a)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// [`approval_check`] without the clock: the canonical form and every member's rule, not the expiry. For reading
|
||||||
|
/// what a refused or expired request said; never enough to sign.
|
||||||
|
pub fn approval_parse(text: &str) -> Result<Approval, Error> {
|
||||||
|
let err = |why: &'static str| Err(Error::Approval(why));
|
||||||
|
if text.len() > MAX_APPROVAL {
|
||||||
|
return err("larger than 8 KiB");
|
||||||
|
}
|
||||||
|
let Ok(j) = serde_json::from_str::<ApprovalJson>(text) else {
|
||||||
|
return err("not an approval in canonical form");
|
||||||
|
};
|
||||||
|
if j.v != 1 {
|
||||||
|
return err("v is not 1");
|
||||||
|
}
|
||||||
|
let a = Approval {
|
||||||
|
run: j.run,
|
||||||
|
repo: j.repo,
|
||||||
|
commit: j.commit,
|
||||||
|
pipeline: j.pipeline,
|
||||||
|
version: j.version,
|
||||||
|
targets: j.targets,
|
||||||
|
expires: j.expires,
|
||||||
|
};
|
||||||
|
if !run_id_ok(&a.run) {
|
||||||
|
return err("the run is not a run id ([A-Za-z0-9._-], 1 to 64)");
|
||||||
|
}
|
||||||
|
if !name_ok(&a.repo) {
|
||||||
|
return err("the repo is not 1 to 64 of [A-Za-z0-9._+-]");
|
||||||
|
}
|
||||||
|
if a.commit.len() != 40 || !a.commit.bytes().all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c)) {
|
||||||
|
return err("the commit is not 40 lower-case hex digits");
|
||||||
|
}
|
||||||
|
if !name_ok(&a.pipeline) {
|
||||||
|
return err("the pipeline is not 1 to 64 of [A-Za-z0-9._+-]");
|
||||||
|
}
|
||||||
|
if !name_ok(&a.version) {
|
||||||
|
return err("the version is not 1 to 64 of [A-Za-z0-9._+-]");
|
||||||
|
}
|
||||||
|
if !(1..=16).contains(&a.targets.len()) {
|
||||||
|
return err("there must be 1 to 16 targets");
|
||||||
|
}
|
||||||
|
for t in &a.targets {
|
||||||
|
if !(1..=80).contains(&t.chars().count()) {
|
||||||
|
return err("a target is not 1 to 80 characters");
|
||||||
|
}
|
||||||
|
if t.chars().any(unprintable) {
|
||||||
|
return err("a target has control or invisible characters");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if a.canonical() != text {
|
||||||
|
return err("not in canonical form (key order, spaces or escaping)");
|
||||||
|
}
|
||||||
|
Ok(a)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Signs a deploy approval for `run` as prehashed minisign over the text's bytes, file name `approval-<run>.json`.
|
||||||
|
/// The text is checked with [`approval_check`] at `timestamp` (Unix seconds) and must name `run`.
|
||||||
|
pub fn approval(
|
||||||
|
secret: &Ed25519Secret,
|
||||||
|
key_id: &[u8; 8],
|
||||||
|
text: &str,
|
||||||
|
timestamp: u64,
|
||||||
|
run: &str,
|
||||||
|
) -> Result<String, Error> {
|
||||||
|
let a = approval_check(text, timestamp)?;
|
||||||
|
if a.run != run {
|
||||||
|
return Err(Error::Approval("the approval's run is not the request's"));
|
||||||
|
}
|
||||||
|
minisign(secret, key_id, &blake2b512(text.as_bytes()), &format!("approval-{run}.json"), timestamp)
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,209 @@
|
|||||||
|
//! Deploy approvals (docs/SIGNING.md, "approval"): the canonical form is checked byte for byte, and the signature is
|
||||||
|
//! a prehashed minisign over the text that minisign-verify (what Tauri and the hub's tools check with) accepts.
|
||||||
|
|
||||||
|
use custos_sign::*;
|
||||||
|
|
||||||
|
const NOW: u64 = 1_793_000_000;
|
||||||
|
const COMMIT: &str = "3f2a9c1d0e4b5a6978877665544332211aabbccd";
|
||||||
|
|
||||||
|
/// The doc's example, with an expiry 10 minutes after NOW.
|
||||||
|
fn canonical() -> String {
|
||||||
|
format!(
|
||||||
|
r#"{{"v":1,"run":"r-42","repo":"Arca","commit":"{COMMIT}","pipeline":"release","version":"0.7.0","targets":["deploy to nixos-vm","publish to Aula"],"expires":{}}}"#,
|
||||||
|
NOW + 600
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn with(from: &str, to: &str) -> String {
|
||||||
|
let t = canonical();
|
||||||
|
assert!(t.contains(from), "{from:?}");
|
||||||
|
t.replacen(from, to, 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn refused(text: &str, now: u64) -> String {
|
||||||
|
match approval_check(text, now) {
|
||||||
|
Ok(a) => panic!("accepted {text:?}: {a:?}"),
|
||||||
|
Err(e) => e.to_string(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_canonical_approval_is_accepted_and_reads_back() {
|
||||||
|
let a = approval_check(&canonical(), NOW).unwrap();
|
||||||
|
assert_eq!(a.run, "r-42");
|
||||||
|
assert_eq!(a.repo, "Arca");
|
||||||
|
assert_eq!(a.commit, COMMIT);
|
||||||
|
assert_eq!(a.pipeline, "release");
|
||||||
|
assert_eq!(a.version, "0.7.0");
|
||||||
|
assert_eq!(a.targets, ["deploy to nixos-vm", "publish to Aula"]);
|
||||||
|
assert_eq!(a.expires, NOW + 600);
|
||||||
|
assert_eq!(a.canonical(), canonical());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn reordered_keys_spaces_and_other_shapes_are_refused() {
|
||||||
|
let t = canonical();
|
||||||
|
let reordered = with(r#""run":"r-42","repo":"Arca","#, r#""repo":"Arca","run":"r-42","#);
|
||||||
|
let bad = [
|
||||||
|
reordered,
|
||||||
|
t.replace(',', ", "),
|
||||||
|
t.replace(':', ": "),
|
||||||
|
format!("{t}\n"),
|
||||||
|
format!(" {t}"),
|
||||||
|
t.replace("{\"v\"", "{\n\"v\""),
|
||||||
|
with(r#""v":1,"#, r#""v":1,"x":1,"#),
|
||||||
|
with(r#""v":1,"#, ""),
|
||||||
|
with(r#""v":1,"#, r#""v":1,"v":1,"#),
|
||||||
|
with(r#""v":1,"#, r#""v":2,"#),
|
||||||
|
with(r#""v":1,"#, r#""v":1.0,"#),
|
||||||
|
with(r#""v":1,"#, r#""v":"1","#),
|
||||||
|
format!("[{t}]"),
|
||||||
|
"not json".to_string(),
|
||||||
|
String::new(),
|
||||||
|
];
|
||||||
|
for b in &bad {
|
||||||
|
refused(b, NOW);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn escaping_must_be_minimal() {
|
||||||
|
// A quote and a backslash in a target are escaped the one way JSON allows; the result is canonical.
|
||||||
|
let q = with("publish to Aula", r#"say \"hi\" \\ there"#);
|
||||||
|
assert_eq!(approval_check(&q, NOW).unwrap().targets[1], r#"say "hi" \ there"#);
|
||||||
|
// Raw non-ASCII is canonical; the same text through \u escapes is not.
|
||||||
|
let raw = with("publish to Aula", "publikovat na Aulu é");
|
||||||
|
assert!(approval_check(&raw, NOW).is_ok());
|
||||||
|
for b in [
|
||||||
|
with("publish to Aula", r"publikovat na Aulu \u00e9"),
|
||||||
|
with("publish to Aula", r"publish to \u0041ula"),
|
||||||
|
with("publish to Aula", r"publish\/to Aula"),
|
||||||
|
with("r-42", r"r\u002d42"),
|
||||||
|
] {
|
||||||
|
refused(&b, NOW);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_bad_run_repo_pipeline_or_version_is_refused() {
|
||||||
|
for run in ["", "r 42", "r/42", "r\\\\42", "ř-42", &"r".repeat(65)] {
|
||||||
|
let e = refused(&with("\"run\":\"r-42\"", &format!("\"run\":\"{run}\"")), NOW);
|
||||||
|
assert!(e.contains("run"), "{run:?}: {e}");
|
||||||
|
}
|
||||||
|
let ok_run = "a.B_c-9".to_string() + &"x".repeat(57);
|
||||||
|
assert_eq!(ok_run.len(), 64);
|
||||||
|
assert!(approval_check(&with("\"run\":\"r-42\"", &format!("\"run\":\"{ok_run}\"")), NOW).is_ok());
|
||||||
|
for (member, value) in [("repo", "Arca"), ("pipeline", "release"), ("version", "0.7.0")] {
|
||||||
|
let from = format!("\"{member}\":\"{value}\"");
|
||||||
|
for bad in ["", "a b", "a/b", "a:b", &"a".repeat(65)] {
|
||||||
|
let e = refused(&with(&from, &format!("\"{member}\":\"{bad}\"")), NOW);
|
||||||
|
assert!(e.contains(member), "{member} {bad:?}: {e}");
|
||||||
|
}
|
||||||
|
let fine = format!("\"{member}\":\"A.b_c-1+x{}\"", "z".repeat(55));
|
||||||
|
assert!(approval_check(&with(&from, &fine), NOW).is_ok(), "{fine}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_bad_commit_is_refused() {
|
||||||
|
for bad in [COMMIT.to_uppercase(), COMMIT[..39].to_string(), format!("{COMMIT}0"), COMMIT.replace('a', "g")] {
|
||||||
|
let e = refused(&with(COMMIT, &bad), NOW);
|
||||||
|
assert!(e.contains("commit"), "{bad}: {e}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn targets_have_limits() {
|
||||||
|
let list = |ts: &[String]| ts.iter().map(|t| format!("\"{t}\"")).collect::<Vec<_>>().join(",");
|
||||||
|
let from = r#""targets":["deploy to nixos-vm","publish to Aula"]"#;
|
||||||
|
let set = |ts: &[String]| with(from, &format!("\"targets\":[{}]", list(ts)));
|
||||||
|
let n = |k: usize| (0..k).map(|i| format!("deploy to host-{i}")).collect::<Vec<_>>();
|
||||||
|
|
||||||
|
assert!(approval_check(&set(&n(1)), NOW).is_ok());
|
||||||
|
assert!(approval_check(&set(&n(16)), NOW).is_ok());
|
||||||
|
assert!(approval_check(&set(&["é".repeat(80)]), NOW).is_ok(), "80 characters, not bytes");
|
||||||
|
for bad in [
|
||||||
|
set(&[]),
|
||||||
|
set(&n(17)),
|
||||||
|
set(&[String::new()]),
|
||||||
|
set(&["x".repeat(81)]),
|
||||||
|
set(&["tab\\there".to_string()]),
|
||||||
|
set(&["line\\nbreak".to_string()]),
|
||||||
|
set(&["nul\\u0000".to_string()]),
|
||||||
|
set(&["del\u{7f}".to_string()]),
|
||||||
|
set(&["right-to-left \u{202e}evil".to_string()]),
|
||||||
|
set(&["zero\u{200b}width".to_string()]),
|
||||||
|
with(from, r#""targets":"deploy to nixos-vm""#),
|
||||||
|
with(from, r#""targets":[1]"#),
|
||||||
|
] {
|
||||||
|
let e = refused(&bad, NOW);
|
||||||
|
assert!(e.contains("target") || e.contains("form"), "{bad}: {e}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_expiry_is_after_now_and_within_an_hour() {
|
||||||
|
let at = |exp: u64| with(&format!("\"expires\":{}", NOW + 600), &format!("\"expires\":{exp}"));
|
||||||
|
assert!(approval_check(&at(NOW + 1), NOW).is_ok());
|
||||||
|
assert!(approval_check(&at(NOW + 3600), NOW).is_ok());
|
||||||
|
for exp in [NOW, NOW - 1, 0, NOW + 3601, u64::MAX] {
|
||||||
|
let e = refused(&at(exp), NOW);
|
||||||
|
assert!(e.contains("expire"), "{exp}: {e}");
|
||||||
|
}
|
||||||
|
// The same text expires as time passes.
|
||||||
|
assert!(refused(&canonical(), NOW + 600).contains("expire"));
|
||||||
|
for bad in
|
||||||
|
[format!("\"expires\":{}.0", NOW + 600), format!("\"expires\":-{}", NOW + 600), "\"expires\":\"1\"".into()]
|
||||||
|
{
|
||||||
|
refused(&with(&format!("\"expires\":{}", NOW + 600), &bad), NOW);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_oversized_text_is_refused_before_parsing() {
|
||||||
|
let huge = with("publish to Aula", &"x".repeat(MAX_APPROVAL));
|
||||||
|
assert!(refused(&huge, NOW).contains("larger"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_approval_signature_verifies_with_minisign() {
|
||||||
|
let k = new_ed25519();
|
||||||
|
let text = canonical();
|
||||||
|
let sig = approval(&k.secret, &k.key_id, &text, NOW, "r-42").unwrap();
|
||||||
|
let public = minisign_verify::PublicKey::decode(&minisign_public(&k.public, &k.key_id)).unwrap();
|
||||||
|
let decoded = minisign_verify::Signature::decode(&sig).unwrap();
|
||||||
|
public.verify(text.as_bytes(), &decoded, false).unwrap();
|
||||||
|
assert!(public.verify(with("Arca", "Fabrica").as_bytes(), &decoded, false).is_err());
|
||||||
|
assert_eq!(decoded.trusted_comment(), format!("timestamp:{NOW}\tfile:approval-r-42.json\thashed"));
|
||||||
|
assert!(sig.ends_with('\n'));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn approval_signs_only_a_valid_text_for_its_own_run() {
|
||||||
|
let k = new_ed25519();
|
||||||
|
let e = approval(&k.secret, &k.key_id, &canonical(), NOW, "r-43").unwrap_err();
|
||||||
|
assert!(e.to_string().contains("run"), "{e}");
|
||||||
|
assert!(approval(&k.secret, &k.key_id, &format!("{}\n", canonical()), NOW, "r-42").is_err());
|
||||||
|
assert!(approval(&k.secret, &k.key_id, &canonical(), NOW + 600, "r-42").is_err(), "expired at signing time");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parse_reads_the_form_without_the_clock() {
|
||||||
|
// For the audit of a refused or expired request: everything but the expiry is checked.
|
||||||
|
let a = approval_parse(&canonical()).unwrap();
|
||||||
|
assert_eq!(a, approval_check(&canonical(), NOW).unwrap());
|
||||||
|
assert!(approval_check(&canonical(), NOW + 10_000).is_err());
|
||||||
|
assert_eq!(approval_parse(&canonical()).unwrap().expires, NOW + 600);
|
||||||
|
assert!(approval_parse(&canonical().replace(',', ", ")).is_err());
|
||||||
|
assert!(approval_parse(&with("\"run\":\"r-42\"", "\"run\":\"r 42\"")).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn run_ids_follow_the_rule() {
|
||||||
|
for ok in ["r-42", "setup-1", "a.b_c", &"x".repeat(64)] {
|
||||||
|
assert!(run_id_ok(ok), "{ok}");
|
||||||
|
}
|
||||||
|
for bad in ["", "a b", "a/b", "ř", &"x".repeat(65)] {
|
||||||
|
assert!(!run_id_ok(bad), "{bad}");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
//! The Domi identity's root key (docs/IDENTITY.md). It lives in the vault body and never leaves it: nothing
|
//! The Domi identity's root key (docs/IDENTITY.md). It lives in the vault body and never leaves it: nothing
|
||||||
//! here or on [`Vault`] returns it, and the vault signs nothing with it but subkey certificates.
|
//! here or on [`Vault`] returns it, and the vault signs nothing with it but subkey certificates and
|
||||||
|
//! revocations of keys the person revoked. It derives each app's backup secret from it.
|
||||||
//!
|
//!
|
||||||
//! Creating it is a typestate, so the mnemonic is always shown before the root exists:
|
//! Creating it is a typestate, so the mnemonic is always shown before the root exists:
|
||||||
//!
|
//!
|
||||||
@@ -46,6 +47,13 @@ use zeroize::Zeroizing;
|
|||||||
/// The root signs `CERT_DOMAIN ‖ tbs`, and only a `tbs` that starts with `CERT_MAGIC ‖ its public key`.
|
/// The root signs `CERT_DOMAIN ‖ tbs`, and only a `tbs` that starts with `CERT_MAGIC ‖ its public key`.
|
||||||
const CERT_DOMAIN: &[u8] = b"tessera cert v1\0";
|
const CERT_DOMAIN: &[u8] = b"tessera cert v1\0";
|
||||||
const CERT_MAGIC: &[u8] = b"TSC1";
|
const CERT_MAGIC: &[u8] = b"TSC1";
|
||||||
|
/// And `REVOKE_DOMAIN ‖ tbs`, only for a `tbs` that starts with `REVOKE_MAGIC ‖ its public key ‖ a key the
|
||||||
|
/// person revoked ‖ that key's revoked_at` (Fundamentum docs/TESSERA.md §12).
|
||||||
|
const REVOKE_DOMAIN: &[u8] = b"tessera revoke v1\0";
|
||||||
|
const REVOKE_MAGIC: &[u8] = b"TRV1";
|
||||||
|
/// magic 4, root 32, subkey 32, revoked_at 8, part 2, parts 2, count 4.
|
||||||
|
const REVOKE_HEADER: usize = 84;
|
||||||
|
const BACKUP_SALT: &[u8] = b"tessera backup v1";
|
||||||
const WORDS: usize = 24;
|
const WORDS: usize = 24;
|
||||||
|
|
||||||
/// Step 1: fresh entropy. Nothing is derived from it until the words have been shown.
|
/// Step 1: fresh entropy. Nothing is derived from it until the words have been shown.
|
||||||
@@ -111,6 +119,26 @@ impl Enrollment {
|
|||||||
display(&words);
|
display(&words);
|
||||||
Shown { entropy: self.entropy, challenge: random_challenge() }
|
Shown { entropy: self.entropy, challenge: random_challenge() }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Restores an identity from its whole phrase, typed back (docs/IDENTITY.md, "Restoring it"): all 24
|
||||||
|
/// words prove more than three. Any case, any spacing. Anything that is not 24 English BIP39 words with a
|
||||||
|
/// valid checksum is [`Error::NotAMnemonic`], which names no word.
|
||||||
|
pub fn restore(phrase: &str) -> Result<Confirmed, Error> {
|
||||||
|
// Room for lowercasing without a reallocation that would leave a copy behind.
|
||||||
|
let mut joined = Zeroizing::new(String::with_capacity(phrase.len() * 3 + 1));
|
||||||
|
for (i, w) in phrase.split_whitespace().enumerate() {
|
||||||
|
if i > 0 {
|
||||||
|
joined.push(' ');
|
||||||
|
}
|
||||||
|
joined.extend(w.chars().flat_map(char::to_lowercase));
|
||||||
|
}
|
||||||
|
if joined.split(' ').count() != WORDS {
|
||||||
|
return Err(Error::NotAMnemonic);
|
||||||
|
}
|
||||||
|
let m =
|
||||||
|
bip39::Mnemonic::parse_in_normalized(bip39::Language::English, &joined).map_err(|_| Error::NotAMnemonic)?;
|
||||||
|
Ok(Confirmed { secret: crypto::domi_root_secret(&m) })
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Shown {
|
impl Shown {
|
||||||
@@ -165,7 +193,7 @@ impl fmt::Debug for Confirmed {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// A cert the vault signed, for display (docs/IDENTITY.md). A record, not a trust list.
|
/// A cert the vault signed, for display (docs/IDENTITY.md). A record, not a trust list.
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
pub struct Issued {
|
pub struct Issued {
|
||||||
/// `app` or `device`.
|
/// `app` or `device`.
|
||||||
pub kind: String,
|
pub kind: String,
|
||||||
@@ -180,6 +208,12 @@ pub struct Issued {
|
|||||||
pub not_after: u64,
|
pub not_after: u64,
|
||||||
/// Unix milliseconds.
|
/// Unix milliseconds.
|
||||||
pub issued: i64,
|
pub issued: i64,
|
||||||
|
/// Unix seconds: when the person revoked the key (core 0.10.0).
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub revoked_at: Option<u64>,
|
||||||
|
/// The signed `TRV1` statements, base64url, once an app sent the events to keep.
|
||||||
|
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||||
|
pub revocation: Vec<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The identity in an unlocked vault.
|
/// The identity in an unlocked vault.
|
||||||
@@ -212,6 +246,45 @@ impl Root {
|
|||||||
Ok(crypto::ed25519_sign(&self.secret, &msg))
|
Ok(crypto::ed25519_sign(&self.secret, &msg))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub(crate) fn sign_revocation(&self, tbs: &[u8]) -> Result<[u8; 64], Error> {
|
||||||
|
let names_me = tbs.len() >= REVOKE_HEADER && &tbs[..4] == REVOKE_MAGIC && tbs[4..36] == self.public;
|
||||||
|
if !names_me {
|
||||||
|
return Err(Error::NotARevocation);
|
||||||
|
}
|
||||||
|
let subkey = data_encoding::BASE64URL_NOPAD.encode(&tbs[36..68]);
|
||||||
|
let at = u64::from_be_bytes(tbs[68..76].try_into().expect("8 bytes"));
|
||||||
|
if !self.issued.iter().any(|i| i.subkey == subkey && i.revoked_at == Some(at)) {
|
||||||
|
return Err(Error::NotARevocation);
|
||||||
|
}
|
||||||
|
let msg = Zeroizing::new([REVOKE_DOMAIN, tbs].concat());
|
||||||
|
Ok(crypto::ed25519_sign(&self.secret, &msg))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Marks every cert of `subkey` revoked; keeps the earliest time if one was marked before.
|
||||||
|
pub(crate) fn mark_revoked(&mut self, subkey: &str, at: u64) -> Result<u64, Error> {
|
||||||
|
let mut certs = self.issued.iter().filter(|i| i.subkey == subkey).peekable();
|
||||||
|
if certs.peek().is_none() {
|
||||||
|
return Err(Error::UnknownKey);
|
||||||
|
}
|
||||||
|
let at = certs.filter_map(|i| i.revoked_at).min().unwrap_or(at);
|
||||||
|
self.issued.iter_mut().filter(|i| i.subkey == subkey).for_each(|i| i.revoked_at = Some(at));
|
||||||
|
Ok(at)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn record_revocation(&mut self, subkey: &str, statements: Vec<String>) -> Result<(), Error> {
|
||||||
|
let mut certs = self.issued.iter_mut().filter(|i| i.subkey == subkey).peekable();
|
||||||
|
if certs.peek().is_none() {
|
||||||
|
return Err(Error::UnknownKey);
|
||||||
|
}
|
||||||
|
certs.for_each(|i| i.revocation = statements.clone());
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `HKDF-SHA256(salt "tessera backup v1", ikm = root secret, info = app id)` (docs/IDENTITY.md).
|
||||||
|
pub(crate) fn backup_secret(&self, app_id: &str) -> Zeroizing<[u8; KEY_LEN]> {
|
||||||
|
crypto::hkdf(self.secret.as_ref(), BACKUP_SALT, app_id.as_bytes())
|
||||||
|
}
|
||||||
|
|
||||||
pub(crate) fn json(&self) -> RootJson {
|
pub(crate) fn json(&self) -> RootJson {
|
||||||
RootJson {
|
RootJson {
|
||||||
root: SecretString::new(hex(self.secret.as_ref())),
|
root: SecretString::new(hex(self.secret.as_ref())),
|
||||||
|
|||||||
@@ -21,8 +21,10 @@ mod device;
|
|||||||
mod format;
|
mod format;
|
||||||
pub mod identity;
|
pub mod identity;
|
||||||
mod item;
|
mod item;
|
||||||
|
pub mod provision;
|
||||||
mod save;
|
mod save;
|
||||||
mod secret;
|
mod secret;
|
||||||
|
pub mod security;
|
||||||
pub mod signing;
|
pub mod signing;
|
||||||
|
|
||||||
pub use item::{Attachment, Field, HISTORY_LIMIT, HistoryEntry, Item, ItemType, new_id, now_ms};
|
pub use item::{Attachment, Field, HISTORY_LIMIT, HistoryEntry, Item, ItemType, new_id, now_ms};
|
||||||
@@ -71,8 +73,20 @@ pub enum Error {
|
|||||||
NotACert,
|
NotACert,
|
||||||
#[error("those words are not the ones in the recovery phrase")]
|
#[error("those words are not the ones in the recovery phrase")]
|
||||||
WrongWords,
|
WrongWords,
|
||||||
|
#[error("these are not the 24 words of a recovery phrase: check each word and their order")]
|
||||||
|
NotAMnemonic,
|
||||||
|
#[error("the Domi identity signs a revocation only for a key revoked in Custos, at the time it was revoked")]
|
||||||
|
NotARevocation,
|
||||||
|
#[error("the Domi identity did not certify this key")]
|
||||||
|
UnknownKey,
|
||||||
#[error("this vault already has {0} signing keys")]
|
#[error("this vault already has {0} signing keys")]
|
||||||
SigningExists(&'static str),
|
SigningExists(&'static str),
|
||||||
|
/// Names the member that does not fit (docs/FORMAT.md), never its value.
|
||||||
|
#[error("provision audit: {0}")]
|
||||||
|
Provision(&'static str),
|
||||||
|
/// Names the rule a security change breaks (docs/FORMAT.md, "The security member"), never a value.
|
||||||
|
#[error("security: {0}")]
|
||||||
|
Security(&'static str),
|
||||||
#[error("signing keys: {0}")]
|
#[error("signing keys: {0}")]
|
||||||
Signing(String),
|
Signing(String),
|
||||||
#[error("{0}")]
|
#[error("{0}")]
|
||||||
@@ -268,6 +282,10 @@ struct Body {
|
|||||||
identity: Option<identity::RootJson>,
|
identity: Option<identity::RootJson>,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
signing: Option<signing::StoreJson>,
|
signing: Option<signing::StoreJson>,
|
||||||
|
#[serde(default)]
|
||||||
|
provision: Option<provision::ProvisionJson>,
|
||||||
|
#[serde(default)]
|
||||||
|
security: Option<security::State>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// What `to_bytes` serializes: borrows the items instead of cloning every secret.
|
/// What `to_bytes` serializes: borrows the items instead of cloning every secret.
|
||||||
@@ -281,6 +299,10 @@ struct BodyRef<'a> {
|
|||||||
identity: Option<identity::RootJson>,
|
identity: Option<identity::RootJson>,
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
signing: Option<signing::StoreJson>,
|
signing: Option<signing::StoreJson>,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
provision: Option<provision::ProvisionJson>,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
security: Option<security::State>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// An unlocked vault: the vault key and the decrypted items, both wiped on drop.
|
/// An unlocked vault: the vault key and the decrypted items, both wiped on drop.
|
||||||
@@ -297,6 +319,10 @@ pub struct Vault {
|
|||||||
identity: Option<identity::Root>,
|
identity: Option<identity::Root>,
|
||||||
/// Signing keys and their audit log (docs/SIGNING.md); no key is ever handed out.
|
/// Signing keys and their audit log (docs/SIGNING.md); no key is ever handed out.
|
||||||
signing: signing::Store,
|
signing: signing::Store,
|
||||||
|
/// The Provisio audit (docs/FORMAT.md), oldest first.
|
||||||
|
provision: Vec<provision::ProvisionEntry>,
|
||||||
|
/// The security level's Setup window, the checklist and their audit (docs/FORMAT.md).
|
||||||
|
security: security::State,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl fmt::Debug for Vault {
|
impl fmt::Debug for Vault {
|
||||||
@@ -397,6 +423,8 @@ impl Vault {
|
|||||||
kdf_new: kdf,
|
kdf_new: kdf,
|
||||||
identity: None,
|
identity: None,
|
||||||
signing: signing::Store::default(),
|
signing: signing::Store::default(),
|
||||||
|
provision: Vec::new(),
|
||||||
|
security: security::State::default(),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -414,6 +442,8 @@ impl Vault {
|
|||||||
kdf_new: kdf,
|
kdf_new: kdf,
|
||||||
identity: None,
|
identity: None,
|
||||||
signing: signing::Store::default(),
|
signing: signing::Store::default(),
|
||||||
|
provision: Vec::new(),
|
||||||
|
security: security::State::default(),
|
||||||
};
|
};
|
||||||
v.add_factor(a, label_a)?;
|
v.add_factor(a, label_a)?;
|
||||||
v.add_factor(b, label_b)?;
|
v.add_factor(b, label_b)?;
|
||||||
@@ -447,6 +477,8 @@ impl Vault {
|
|||||||
kdf_new: KdfParams::DEFAULT,
|
kdf_new: KdfParams::DEFAULT,
|
||||||
identity: None,
|
identity: None,
|
||||||
signing: signing::Store::default(),
|
signing: signing::Store::default(),
|
||||||
|
provision: Vec::new(),
|
||||||
|
security: security::State::default(),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -572,6 +604,7 @@ impl Vault {
|
|||||||
Some(j) => signing::Store::from_json(j).ok_or(Error::Corrupted)?,
|
Some(j) => signing::Store::from_json(j).ok_or(Error::Corrupted)?,
|
||||||
None => signing::Store::default(),
|
None => signing::Store::default(),
|
||||||
};
|
};
|
||||||
|
let security = security::State::from_json(body.security).ok_or(Error::Corrupted)?;
|
||||||
Ok(Vault {
|
Ok(Vault {
|
||||||
key,
|
key,
|
||||||
version: header.version,
|
version: header.version,
|
||||||
@@ -581,6 +614,8 @@ impl Vault {
|
|||||||
kdf_new,
|
kdf_new,
|
||||||
identity,
|
identity,
|
||||||
signing,
|
signing,
|
||||||
|
provision: provision::from_json(body.provision),
|
||||||
|
security,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -616,6 +651,8 @@ impl Vault {
|
|||||||
factors: self.factors.iter().map(FactorRec::json).collect(),
|
factors: self.factors.iter().map(FactorRec::json).collect(),
|
||||||
identity: self.identity.as_ref().map(identity::Root::json),
|
identity: self.identity.as_ref().map(identity::Root::json),
|
||||||
signing: self.signing.json(),
|
signing: self.signing.json(),
|
||||||
|
provision: provision::json(&self.provision),
|
||||||
|
security: self.security.json(),
|
||||||
};
|
};
|
||||||
serde_json::to_writer(&mut *json, &body).map_err(|e| Error::Io(std::io::Error::other(e.to_string())))?;
|
serde_json::to_writer(&mut *json, &body).map_err(|e| Error::Io(std::io::Error::other(e.to_string())))?;
|
||||||
let sealed = crypto::seal(&self.key, &body_nonce, &json, &out);
|
let sealed = crypto::seal(&self.key, &body_nonce, &json, &out);
|
||||||
@@ -828,4 +865,27 @@ impl Vault {
|
|||||||
self.identity.as_mut().ok_or(Error::NoIdentity)?.issued.push(issued);
|
self.identity.as_mut().ok_or(Error::NoIdentity)?.issued.push(issued);
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The person revoked the key `subkey` (base64url): marks every cert of it. Returns the revocation time in
|
||||||
|
/// effect, the earlier one if it was marked before. The caller saves the vault.
|
||||||
|
pub fn domi_mark_revoked(&mut self, subkey: &str, revoked_at: u64) -> Result<u64, Error> {
|
||||||
|
self.identity.as_mut().ok_or(Error::NoIdentity)?.mark_revoked(subkey, revoked_at)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Ed25519 with the root over `"tessera revoke v1\0" ‖ tbs`, for a `tbs` that starts with `TRV1`, this
|
||||||
|
/// root's public key, a key marked revoked and its `revoked_at` ([`Error::NotARevocation`] otherwise).
|
||||||
|
pub fn domi_sign_revocation(&self, tbs: &[u8]) -> Result<[u8; 64], Error> {
|
||||||
|
self.identity.as_ref().ok_or(Error::NoIdentity)?.sign_revocation(tbs)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Keeps the signed statements (base64url `TRV1`) with every cert of `subkey`. The caller saves the vault.
|
||||||
|
pub fn domi_record_revocation(&mut self, subkey: &str, statements: Vec<String>) -> Result<(), Error> {
|
||||||
|
self.identity.as_mut().ok_or(Error::NoIdentity)?.record_revocation(subkey, statements)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The backup secret of the app `app_id` (docs/IDENTITY.md): derived from the root, handed to that app
|
||||||
|
/// only. The caller checks `app_id` (a-z, 0-9, `-`) and the app's right to it.
|
||||||
|
pub fn domi_backup_secret(&self, app_id: &str) -> Result<Zeroizing<[u8; 32]>, Error> {
|
||||||
|
Ok(self.identity.as_ref().ok_or(Error::NoIdentity)?.backup_secret(app_id))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,233 @@
|
|||||||
|
//! The Provisio audit (docs/FORMAT.md, "The provision audit"): the vault body member `provision`, beside
|
||||||
|
//! signing's audit. One entry per outcome of a server's ask or offer. An entry holds no secret: every member is
|
||||||
|
//! something the server sent in the clear through the mailbox, or the match code of a public key.
|
||||||
|
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
use crate::{Error, Vault};
|
||||||
|
|
||||||
|
/// The log keeps the newest this many entries.
|
||||||
|
pub const AUDIT_LIMIT: usize = 5_000;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "lowercase")]
|
||||||
|
pub enum Direction {
|
||||||
|
/// The server asked Custos for a secret (or asked it to make one).
|
||||||
|
Ask,
|
||||||
|
/// The server offered a secret it made.
|
||||||
|
Offer,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "lowercase")]
|
||||||
|
pub enum Store {
|
||||||
|
/// A Domi-ref item in the vault.
|
||||||
|
Vault,
|
||||||
|
/// The local Claude Code store.
|
||||||
|
Claude,
|
||||||
|
/// The cloud Claude Code store.
|
||||||
|
Cloud,
|
||||||
|
/// Shown once on the card and stored nowhere: a display offer (core 0.12.0).
|
||||||
|
Display,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "kebab-case")]
|
||||||
|
pub enum Outcome {
|
||||||
|
/// Ask: Mark approved; the item's value was sealed to the request.
|
||||||
|
Approved,
|
||||||
|
/// Ask with `--generate`: Custos made the item, stored it and sealed it to the request.
|
||||||
|
Generated,
|
||||||
|
/// Offer: Mark accepted; the value was stored.
|
||||||
|
Accepted,
|
||||||
|
/// Mark refused on the card.
|
||||||
|
Refused,
|
||||||
|
/// Outside the scope: refused before a card, or again when storing.
|
||||||
|
OutOfScope,
|
||||||
|
/// An offer's box did not match the offer (item, store, kind or code key), or did not open.
|
||||||
|
Invalid,
|
||||||
|
/// Nobody answered within five minutes.
|
||||||
|
Expired,
|
||||||
|
/// A display offer: Mark typed the code the phone shows, Custos checked it and sent it (core 0.12.0).
|
||||||
|
Confirmed,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One audit entry. Append-only: nothing edits or removes one.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct ProvisionEntry {
|
||||||
|
/// Unix milliseconds.
|
||||||
|
pub at: i64,
|
||||||
|
pub direction: Direction,
|
||||||
|
/// The name the factor service gave the server.
|
||||||
|
pub host: String,
|
||||||
|
pub item: String,
|
||||||
|
pub store: Store,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub run: Option<String>,
|
||||||
|
/// An offer's label (`--kind`), or an ask's `--generate` recipe.
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub kind: Option<String>,
|
||||||
|
/// The match code both screens showed: six digits.
|
||||||
|
pub code: String,
|
||||||
|
pub outcome: Outcome,
|
||||||
|
/// An accepted offer replaced an existing item.
|
||||||
|
#[serde(default)]
|
||||||
|
pub replaced: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The body member: `{"audit": [...]}`.
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
pub(crate) struct ProvisionJson {
|
||||||
|
#[serde(default)]
|
||||||
|
audit: Vec<ProvisionEntry>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The log as the vault keeps it, oldest first.
|
||||||
|
pub(crate) fn from_json(j: Option<ProvisionJson>) -> Vec<ProvisionEntry> {
|
||||||
|
let mut audit = j.map(|j| j.audit).unwrap_or_default();
|
||||||
|
trim(&mut audit);
|
||||||
|
audit
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Absent while the log is empty, so a vault without entries is written exactly as before.
|
||||||
|
pub(crate) fn json(audit: &[ProvisionEntry]) -> Option<ProvisionJson> {
|
||||||
|
(!audit.is_empty()).then(|| ProvisionJson { audit: audit.to_vec() })
|
||||||
|
}
|
||||||
|
|
||||||
|
fn trim(audit: &mut Vec<ProvisionEntry>) {
|
||||||
|
if audit.len() > AUDIT_LIMIT {
|
||||||
|
audit.drain(..audit.len() - AUDIT_LIMIT);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `^[a-z0-9][a-z0-9._-]{0,63}(/[a-z0-9][a-z0-9._-]{0,63}){0,3}$`, as the factor service checks an item.
|
||||||
|
fn item_ok(item: &str) -> bool {
|
||||||
|
let parts: Vec<&str> = item.split('/').collect();
|
||||||
|
parts.len() <= 4
|
||||||
|
&& parts.iter().all(|p| {
|
||||||
|
let b = p.as_bytes();
|
||||||
|
(1..=64).contains(&b.len())
|
||||||
|
&& (b[0].is_ascii_lowercase() || b[0].is_ascii_digit())
|
||||||
|
&& b.iter().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || b"._-".contains(c))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ProvisionEntry {
|
||||||
|
/// Whether every member fits docs/FORMAT.md. The error names the member, never its value.
|
||||||
|
pub fn check(&self) -> Result<(), Error> {
|
||||||
|
let host = self.host.as_bytes();
|
||||||
|
if !(1..=253).contains(&host.len()) || !host.iter().all(|c| c.is_ascii_alphanumeric() || b".-".contains(c)) {
|
||||||
|
return Err(Error::Provision("the host is not a host name"));
|
||||||
|
}
|
||||||
|
if !item_ok(&self.item) {
|
||||||
|
return Err(Error::Provision("the item is not an item name"));
|
||||||
|
}
|
||||||
|
if let Some(run) = &self.run {
|
||||||
|
let r = run.as_bytes();
|
||||||
|
if !(1..=64).contains(&r.len()) || !r.iter().all(|c| c.is_ascii_alphanumeric() || b"._-".contains(c)) {
|
||||||
|
return Err(Error::Provision("the run is not a run id"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some(kind) = &self.kind
|
||||||
|
&& (kind.chars().count() > 200 || kind.chars().any(char::is_control))
|
||||||
|
{
|
||||||
|
return Err(Error::Provision("the kind is longer than 200 characters or has control characters"));
|
||||||
|
}
|
||||||
|
if self.code.len() != 6 || !self.code.bytes().all(|c| c.is_ascii_digit()) {
|
||||||
|
return Err(Error::Provision("the match code is not six digits"));
|
||||||
|
}
|
||||||
|
// A display offer stores nothing; `confirmed` is its outcome and nobody else's.
|
||||||
|
if self.store == Store::Display {
|
||||||
|
if self.direction != Direction::Offer {
|
||||||
|
return Err(Error::Provision("a display is an offer"));
|
||||||
|
}
|
||||||
|
if matches!(self.outcome, Outcome::Accepted | Outcome::Approved | Outcome::Generated) || self.replaced {
|
||||||
|
return Err(Error::Provision("a display offer stores nothing"));
|
||||||
|
}
|
||||||
|
} else if self.outcome == Outcome::Confirmed {
|
||||||
|
return Err(Error::Provision("only a display offer is confirmed"));
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Vault {
|
||||||
|
/// Records one outcome, after `ProvisionEntry::check`. Beyond `AUDIT_LIMIT` entries the oldest goes. The
|
||||||
|
/// caller saves.
|
||||||
|
pub fn provision_record(&mut self, entry: ProvisionEntry) -> Result<(), Error> {
|
||||||
|
entry.check()?;
|
||||||
|
self.provision.push(entry);
|
||||||
|
trim(&mut self.provision);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Every outcome, oldest first (newest last).
|
||||||
|
pub fn provision_audit(&self) -> &[ProvisionEntry] {
|
||||||
|
&self.provision
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
//! An older reader still opens a vault with the member. It lives here because only the crate can decrypt the
|
||||||
|
//! body and parse it the way core 0.10.0 did.
|
||||||
|
use super::*;
|
||||||
|
use crate::format::Header;
|
||||||
|
use crate::{FactorJson, Item, ItemType, KdfParams, SecretString, crypto, identity, signing};
|
||||||
|
|
||||||
|
/// The body as core 0.10.0 parsed it (src/lib.rs `Body` at v0.10.0): no `provision`.
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
#[allow(dead_code)]
|
||||||
|
struct BodyV0_10 {
|
||||||
|
format: u32,
|
||||||
|
items: Vec<Item>,
|
||||||
|
#[serde(default)]
|
||||||
|
factors: Vec<FactorJson>,
|
||||||
|
#[serde(default)]
|
||||||
|
identity: Option<identity::RootJson>,
|
||||||
|
#[serde(default)]
|
||||||
|
signing: Option<signing::StoreJson>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn body_json(v: &Vault) -> String {
|
||||||
|
let bytes = v.to_bytes().unwrap();
|
||||||
|
let (header, at) = Header::parse(&bytes).unwrap();
|
||||||
|
let json = crypto::open(&v.key, &header.body_nonce, &bytes[at..], &bytes[..at]).unwrap();
|
||||||
|
String::from_utf8(json.to_vec()).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn entry() -> ProvisionEntry {
|
||||||
|
ProvisionEntry {
|
||||||
|
at: 1_793_750_000_000,
|
||||||
|
direction: Direction::Offer,
|
||||||
|
host: "nixos-vm".into(),
|
||||||
|
item: "arca/gitea-read-token".into(),
|
||||||
|
store: Store::Vault,
|
||||||
|
run: None,
|
||||||
|
kind: Some("Gitea token, read:repository".into()),
|
||||||
|
code: "684361".into(),
|
||||||
|
outcome: Outcome::Accepted,
|
||||||
|
replaced: true,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_older_reader_opens_a_vault_with_the_provision_audit() {
|
||||||
|
let mut v =
|
||||||
|
Vault::create(&SecretString::from("pw"), KdfParams { m_cost_kib: 64, t_cost: 1, p_cost: 1 }).unwrap();
|
||||||
|
v.add(Item::new(ItemType::SecureNote, "kept", 1));
|
||||||
|
// Without entries the body has no trace of the member, so it is byte-for-byte what 0.10.0 wrote.
|
||||||
|
assert!(!body_json(&v).contains("provision"));
|
||||||
|
|
||||||
|
v.provision_record(entry()).unwrap();
|
||||||
|
let json = body_json(&v);
|
||||||
|
assert!(json.contains(r#""provision":{"audit":[{"#), "{json}");
|
||||||
|
// Core 0.10.0's parser takes it and keeps everything it knows.
|
||||||
|
let old: BodyV0_10 = serde_json::from_str(&json).unwrap();
|
||||||
|
assert_eq!(old.format, 1);
|
||||||
|
assert_eq!(old.items.len(), 1);
|
||||||
|
assert_eq!(old.items[0].title, "kept");
|
||||||
|
assert!(old.identity.is_none() && old.signing.is_none());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,623 @@
|
|||||||
|
//! The security level and the hardening checklist (docs/FORMAT.md, "The security member"): the vault body member
|
||||||
|
//! `security`. The level is computed from the Setup window and the ticked items, never stored; every change is in an
|
||||||
|
//! append-only audit. Nothing here is secret.
|
||||||
|
|
||||||
|
use std::collections::BTreeSet;
|
||||||
|
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
use crate::{Error, Vault};
|
||||||
|
|
||||||
|
/// The log keeps the newest this many entries.
|
||||||
|
pub const AUDIT_LIMIT: usize = 5_000;
|
||||||
|
/// How long Setup lasts from *Connect via SSH*, in milliseconds: 2 hours.
|
||||||
|
pub const SETUP_WINDOW: i64 = 2 * 60 * 60 * 1000;
|
||||||
|
|
||||||
|
/// A checklist item.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "kebab-case")]
|
||||||
|
pub enum Item {
|
||||||
|
/// Move the Authelia TOTP to my phone.
|
||||||
|
TotpOnPhone,
|
||||||
|
/// Approve with Windows Hello.
|
||||||
|
HelloApprovals,
|
||||||
|
/// Narrow the server scope.
|
||||||
|
NarrowScope,
|
||||||
|
/// Rotate what setup made.
|
||||||
|
RotateSetup,
|
||||||
|
/// Turn off Connect via SSH.
|
||||||
|
NoSsh,
|
||||||
|
/// The phone approves this PC.
|
||||||
|
PhoneApproves,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "lowercase")]
|
||||||
|
pub enum Level {
|
||||||
|
/// From *Connect via SSH* until 2 hours later or *Finish setup*.
|
||||||
|
Setup,
|
||||||
|
/// After Setup, and every vault that never had one.
|
||||||
|
Standard,
|
||||||
|
/// Not in Setup, and at least one checklist item ticked.
|
||||||
|
Hardened,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How an undo was confirmed.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "lowercase")]
|
||||||
|
pub enum Auth {
|
||||||
|
Hello,
|
||||||
|
Password,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "kebab-case")]
|
||||||
|
pub enum Action {
|
||||||
|
SetupStarted,
|
||||||
|
SetupFinished,
|
||||||
|
/// Written by the first change after the window ended on its own.
|
||||||
|
SetupExpired,
|
||||||
|
Ticked,
|
||||||
|
Unticked,
|
||||||
|
SshConnected,
|
||||||
|
TotpMoved,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What *Connect via SSH* needs.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "kebab-case")]
|
||||||
|
pub enum SshRule {
|
||||||
|
/// Offered, one click (Setup).
|
||||||
|
Allowed,
|
||||||
|
/// Offered after Windows Hello or the master password.
|
||||||
|
NeedsAuth,
|
||||||
|
/// Not offered (*Turn off Connect via SSH* is ticked).
|
||||||
|
Off,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A Setup window, Unix milliseconds: Setup holds for `started <= now < until`.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct Window {
|
||||||
|
pub started: i64,
|
||||||
|
pub until: i64,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The server scope prefixes *Narrow the server scope* replaced, kept for its undo.
|
||||||
|
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct KeptScope {
|
||||||
|
#[serde(default)]
|
||||||
|
pub ask: Vec<String>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub offer: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One audit entry. Append-only: nothing edits or removes one.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct SecurityEntry {
|
||||||
|
/// Unix milliseconds.
|
||||||
|
pub at: i64,
|
||||||
|
pub action: Action,
|
||||||
|
/// The checklist item, for `ticked` and `unticked`.
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub item: Option<Item>,
|
||||||
|
/// How an undo was confirmed, for `unticked`.
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub auth: Option<Auth>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Everything *Settings → Security* shows.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct SecurityView {
|
||||||
|
pub level: Level,
|
||||||
|
/// The last Setup window, if there was one.
|
||||||
|
pub setup: Option<Window>,
|
||||||
|
/// When that window ended (Finish setup, or `until` once its expiry was noticed).
|
||||||
|
pub finished: Option<i64>,
|
||||||
|
/// Milliseconds of Setup left, while in Setup.
|
||||||
|
pub setup_remaining: Option<i64>,
|
||||||
|
pub ticked: BTreeSet<Item>,
|
||||||
|
pub kept_scope: Option<KeptScope>,
|
||||||
|
/// Oldest first.
|
||||||
|
pub audit: Vec<SecurityEntry>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The member as the vault keeps it, and as it is written.
|
||||||
|
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub(crate) struct State {
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
setup: Option<Window>,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
finished: Option<i64>,
|
||||||
|
#[serde(default, skip_serializing_if = "BTreeSet::is_empty")]
|
||||||
|
ticked: BTreeSet<Item>,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
kept_scope: Option<KeptScope>,
|
||||||
|
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||||
|
audit: Vec<SecurityEntry>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// At most this many prefixes on each side of a kept scope.
|
||||||
|
const KEPT_MAX: usize = 64;
|
||||||
|
|
||||||
|
/// A kept scope prefix: 1 to 200 characters, no control characters. The error names the rule, never the value.
|
||||||
|
fn kept_ok(list: &[String]) -> Result<(), Error> {
|
||||||
|
if list.len() > KEPT_MAX {
|
||||||
|
return Err(Error::Security("a kept scope has at most 64 prefixes on each side"));
|
||||||
|
}
|
||||||
|
if list.iter().any(|p| !(1..=200).contains(&p.chars().count()) || p.chars().any(char::is_control)) {
|
||||||
|
return Err(Error::Security("a kept scope prefix is 1 to 200 characters without control characters"));
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn trim(audit: &mut Vec<SecurityEntry>) {
|
||||||
|
if audit.len() > AUDIT_LIMIT {
|
||||||
|
audit.drain(..audit.len() - AUDIT_LIMIT);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl State {
|
||||||
|
/// The member as read, checked; `None` when it breaks a rule (the vault then does not open).
|
||||||
|
pub(crate) fn from_json(j: Option<State>) -> Option<State> {
|
||||||
|
let mut st = j.unwrap_or_default();
|
||||||
|
if let Some(w) = st.setup
|
||||||
|
&& w.until <= w.started
|
||||||
|
{
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
if st.finished.is_some() && st.setup.is_none() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
if let Some(k) = &st.kept_scope
|
||||||
|
&& (kept_ok(&k.ask).is_err() || kept_ok(&k.offer).is_err())
|
||||||
|
{
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
trim(&mut st.audit);
|
||||||
|
Some(st)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Absent while nothing was ever set, so a vault without it is written exactly as before.
|
||||||
|
pub(crate) fn json(&self) -> Option<State> {
|
||||||
|
(*self != State::default()).then(|| self.clone())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Setup holds for `started <= now < until` of a window that has not finished.
|
||||||
|
fn in_setup(&self, now: i64) -> bool {
|
||||||
|
self.finished.is_none() && self.setup.is_some_and(|w| w.started <= now && now < w.until)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn level(&self, now: i64) -> Level {
|
||||||
|
if self.in_setup(now) {
|
||||||
|
Level::Setup
|
||||||
|
} else if self.ticked.is_empty() {
|
||||||
|
Level::Standard
|
||||||
|
} else {
|
||||||
|
Level::Hardened
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn push(&mut self, at: i64, action: Action, item: Option<Item>, auth: Option<Auth>) {
|
||||||
|
self.audit.push(SecurityEntry { at, action, item, auth });
|
||||||
|
trim(&mut self.audit);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Before any change: a window that ended on its own is written down once, as `setup-expired` at `now` and
|
||||||
|
/// `finished` = `until`.
|
||||||
|
fn notice_expiry(&mut self, now: i64) {
|
||||||
|
if let Some(w) = self.setup
|
||||||
|
&& self.finished.is_none()
|
||||||
|
&& now >= w.until
|
||||||
|
{
|
||||||
|
self.finished = Some(w.until);
|
||||||
|
self.push(now, Action::SetupExpired, None, None);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// *Accept all* on a run card: only in Setup, for a setup run (its id starts with `setup-`) that holds Provisio
|
||||||
|
/// lines only.
|
||||||
|
pub fn accept_all_allowed(level: Level, run_id: &str, only_provision: bool) -> bool {
|
||||||
|
level == Level::Setup && run_id.starts_with("setup-") && only_provision
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether a line that replaces a stored item starts ticked: only where *Accept all* applies (a setup run in
|
||||||
|
/// Setup); otherwise Mark ticks it himself.
|
||||||
|
pub fn replacing_line_preticked(level: Level, setup_run: bool) -> bool {
|
||||||
|
level == Level::Setup && setup_run
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What *Connect via SSH* needs: off when *Turn off Connect via SSH* is ticked, one click in Setup, Windows Hello or
|
||||||
|
/// the master password otherwise.
|
||||||
|
pub fn ssh_needs_auth(level: Level, ticked: &BTreeSet<Item>) -> SshRule {
|
||||||
|
if ticked.contains(&Item::NoSsh) {
|
||||||
|
SshRule::Off
|
||||||
|
} else if level == Level::Setup {
|
||||||
|
SshRule::Allowed
|
||||||
|
} else {
|
||||||
|
SshRule::NeedsAuth
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether a server may offer a TOTP seed into the vault: not once it was moved to the phone.
|
||||||
|
pub fn totp_offer_allowed(ticked: &BTreeSet<Item>) -> bool {
|
||||||
|
!ticked.contains(&Item::TotpOnPhone)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether *Sign & release*, *Accept*, *Accept all* and approvals ask for Windows Hello first.
|
||||||
|
pub fn hello_for_approvals(ticked: &BTreeSet<Item>) -> bool {
|
||||||
|
ticked.contains(&Item::HelloApprovals)
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Vault {
|
||||||
|
/// The level at `now` (Unix milliseconds).
|
||||||
|
pub fn security_level(&self, now: i64) -> Level {
|
||||||
|
self.security.level(now)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The level, the Setup window and what is left of it, the ticked items, the kept scope and the audit.
|
||||||
|
pub fn security_view(&self, now: i64) -> SecurityView {
|
||||||
|
let st = &self.security;
|
||||||
|
SecurityView {
|
||||||
|
level: st.level(now),
|
||||||
|
setup: st.setup,
|
||||||
|
finished: st.finished,
|
||||||
|
setup_remaining: st.setup.filter(|_| st.in_setup(now)).map(|w| w.until - now),
|
||||||
|
ticked: st.ticked.clone(),
|
||||||
|
kept_scope: st.kept_scope.clone(),
|
||||||
|
audit: st.audit.clone(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Starts Setup (*Connect via SSH*): a window of 2 hours from `now`, audited `setup-started`. While in Setup it
|
||||||
|
/// changes nothing and returns the window that holds. The caller saves.
|
||||||
|
pub fn security_start_setup(&mut self, now: i64) -> Window {
|
||||||
|
let st = &mut self.security;
|
||||||
|
st.notice_expiry(now);
|
||||||
|
if st.in_setup(now)
|
||||||
|
&& let Some(w) = st.setup
|
||||||
|
{
|
||||||
|
return w;
|
||||||
|
}
|
||||||
|
let w = Window { started: now, until: now.saturating_add(SETUP_WINDOW) };
|
||||||
|
st.setup = Some(w);
|
||||||
|
st.finished = None;
|
||||||
|
st.push(now, Action::SetupStarted, None, None);
|
||||||
|
w
|
||||||
|
}
|
||||||
|
|
||||||
|
/// *Finish setup*: ends the window at `now`, audited `setup-finished`. False when not in Setup. The caller saves.
|
||||||
|
pub fn security_finish_setup(&mut self, now: i64) -> bool {
|
||||||
|
let st = &mut self.security;
|
||||||
|
st.notice_expiry(now);
|
||||||
|
if !st.in_setup(now) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
st.finished = Some(now);
|
||||||
|
st.push(now, Action::SetupFinished, None, None);
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Ticks a checklist item, audited `ticked`. False (and no entry) when it was ticked already. The caller saves.
|
||||||
|
pub fn security_tick(&mut self, item: Item, now: i64) -> bool {
|
||||||
|
let st = &mut self.security;
|
||||||
|
st.notice_expiry(now);
|
||||||
|
if !st.ticked.insert(item) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
st.push(now, Action::Ticked, Some(item), None);
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Unticks a checklist item after Windows Hello or the master password, audited `unticked` with how. False (and
|
||||||
|
/// no entry) when it was not ticked. The caller saves.
|
||||||
|
pub fn security_untick(&mut self, item: Item, auth: Auth, now: i64) -> bool {
|
||||||
|
let st = &mut self.security;
|
||||||
|
st.notice_expiry(now);
|
||||||
|
if !st.ticked.remove(&item) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
st.push(now, Action::Unticked, Some(item), Some(auth));
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Keeps the scope prefixes *Narrow the server scope* replaces. Refused when a scope is kept already (its undo
|
||||||
|
/// has not taken it back), so the first prefixes are never lost. The caller saves.
|
||||||
|
pub fn security_keep_scope(&mut self, ask: &[String], offer: &[String]) -> Result<(), Error> {
|
||||||
|
if self.security.kept_scope.is_some() {
|
||||||
|
return Err(Error::Security("a scope is kept already; take it back first"));
|
||||||
|
}
|
||||||
|
kept_ok(ask)?;
|
||||||
|
kept_ok(offer)?;
|
||||||
|
self.security.kept_scope = Some(KeptScope { ask: ask.to_vec(), offer: offer.to_vec() });
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Takes the kept prefixes back, for the undo. The caller saves.
|
||||||
|
pub fn security_take_kept_scope(&mut self) -> Option<KeptScope> {
|
||||||
|
self.security.kept_scope.take()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Records `ssh-connected` or `totp-moved`; the other actions are written by the calls above. The caller saves.
|
||||||
|
pub fn security_record(&mut self, action: Action, item: Option<Item>, now: i64) -> Result<(), Error> {
|
||||||
|
if !matches!(action, Action::SshConnected | Action::TotpMoved) {
|
||||||
|
return Err(Error::Security("only ssh-connected and totp-moved are recorded directly"));
|
||||||
|
}
|
||||||
|
let st = &mut self.security;
|
||||||
|
st.notice_expiry(now);
|
||||||
|
st.push(now, action, item, None);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
//! An older reader still opens a vault with the member, and unknown values make the vault refuse to open. They
|
||||||
|
//! live here because only the crate can decrypt the body, change it and seal it again.
|
||||||
|
use super::*;
|
||||||
|
use crate::format::Header;
|
||||||
|
use crate::{FactorJson, Item as VaultItem, ItemType, KdfParams, SecretString, crypto, identity, provision};
|
||||||
|
|
||||||
|
const NOW: i64 = 1_793_750_000_000;
|
||||||
|
|
||||||
|
fn vault() -> Vault {
|
||||||
|
Vault::create(&SecretString::from("pw"), KdfParams { m_cost_kib: 64, t_cost: 1, p_cost: 1 }).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn body_json(v: &Vault) -> String {
|
||||||
|
let bytes = v.to_bytes().unwrap();
|
||||||
|
let (header, at) = Header::parse(&bytes).unwrap();
|
||||||
|
let json = crypto::open(&v.key, &header.body_nonce, &bytes[at..], &bytes[..at]).unwrap();
|
||||||
|
String::from_utf8(json.to_vec()).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The vault's file with its body replaced by `json`, sealed with the vault's key as `to_bytes` does.
|
||||||
|
fn with_body(v: &Vault, json: &str) -> Vec<u8> {
|
||||||
|
let bytes = v.to_bytes().unwrap();
|
||||||
|
let (header, at) = Header::parse(&bytes).unwrap();
|
||||||
|
let mut out = bytes[..at].to_vec();
|
||||||
|
out.extend_from_slice(&crypto::seal(&v.key, &header.body_nonce, json.as_bytes(), &bytes[..at]));
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- the body as core 0.11.0 parsed it (src/lib.rs, src/signing.rs, src/provision.rs at v0.11.0) ----
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
#[allow(dead_code)]
|
||||||
|
struct BodyV0_11 {
|
||||||
|
format: u32,
|
||||||
|
items: Vec<VaultItem>,
|
||||||
|
#[serde(default)]
|
||||||
|
factors: Vec<FactorJson>,
|
||||||
|
#[serde(default)]
|
||||||
|
identity: Option<identity::RootJson>,
|
||||||
|
#[serde(default)]
|
||||||
|
signing: Option<SigningV0_11>,
|
||||||
|
#[serde(default)]
|
||||||
|
provision: Option<ProvisionV0_11>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
#[allow(dead_code)]
|
||||||
|
struct SigningV0_11 {
|
||||||
|
#[serde(default)]
|
||||||
|
keys: Vec<KeyV0_11>,
|
||||||
|
#[serde(default)]
|
||||||
|
audit: Vec<SignEntryV0_11>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
#[allow(dead_code)]
|
||||||
|
struct KeyV0_11 {
|
||||||
|
id: String,
|
||||||
|
kind: OldKeyKind,
|
||||||
|
role: OldRole,
|
||||||
|
name: String,
|
||||||
|
created: i64,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
#[serde(rename_all = "kebab-case")]
|
||||||
|
enum OldKeyKind {
|
||||||
|
Ed25519,
|
||||||
|
RootCa,
|
||||||
|
CodeSigning,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
#[serde(rename_all = "lowercase")]
|
||||||
|
enum OldRole {
|
||||||
|
Release,
|
||||||
|
Test,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
#[allow(dead_code)]
|
||||||
|
struct SignEntryV0_11 {
|
||||||
|
at: i64,
|
||||||
|
key: String,
|
||||||
|
kind: OldSignKind,
|
||||||
|
outcome: OldSignOutcome,
|
||||||
|
via: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
#[serde(rename_all = "lowercase")]
|
||||||
|
enum OldSignKind {
|
||||||
|
Minisign,
|
||||||
|
Manifest,
|
||||||
|
Authenticode,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
#[serde(rename_all = "kebab-case")]
|
||||||
|
enum OldSignOutcome {
|
||||||
|
Approved,
|
||||||
|
Auto,
|
||||||
|
Refused,
|
||||||
|
Expired,
|
||||||
|
OutOfScope,
|
||||||
|
Invalid,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
#[allow(dead_code)]
|
||||||
|
struct ProvisionV0_11 {
|
||||||
|
#[serde(default)]
|
||||||
|
audit: Vec<ProvisionEntryV0_11>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
#[allow(dead_code)]
|
||||||
|
struct ProvisionEntryV0_11 {
|
||||||
|
store: OldStore,
|
||||||
|
outcome: OldProvisionOutcome,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
#[serde(rename_all = "lowercase")]
|
||||||
|
enum OldStore {
|
||||||
|
Vault,
|
||||||
|
Claude,
|
||||||
|
Cloud,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
#[serde(rename_all = "kebab-case")]
|
||||||
|
enum OldProvisionOutcome {
|
||||||
|
Approved,
|
||||||
|
Generated,
|
||||||
|
Accepted,
|
||||||
|
Refused,
|
||||||
|
OutOfScope,
|
||||||
|
Invalid,
|
||||||
|
Expired,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn display_entry(outcome: provision::Outcome) -> provision::ProvisionEntry {
|
||||||
|
provision::ProvisionEntry {
|
||||||
|
at: NOW,
|
||||||
|
direction: provision::Direction::Offer,
|
||||||
|
host: "nixos-vm".into(),
|
||||||
|
item: "arca/authelia-mark".into(),
|
||||||
|
store: provision::Store::Display,
|
||||||
|
run: None,
|
||||||
|
kind: Some("totp".into()),
|
||||||
|
code: "684361".into(),
|
||||||
|
outcome,
|
||||||
|
replaced: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_older_reader_opens_a_vault_with_the_security_member() {
|
||||||
|
let mut v = vault();
|
||||||
|
v.add(VaultItem::new(ItemType::SecureNote, "kept", 1));
|
||||||
|
// Never set: the body has no trace of the member, so it is byte-for-byte what 0.11.0 wrote.
|
||||||
|
assert!(!body_json(&v).contains("security"));
|
||||||
|
|
||||||
|
v.security_start_setup(NOW);
|
||||||
|
v.security_tick(Item::HelloApprovals, NOW + 1);
|
||||||
|
v.security_untick(Item::HelloApprovals, Auth::Hello, NOW + 2);
|
||||||
|
v.security_tick(Item::NoSsh, NOW + 3);
|
||||||
|
v.security_keep_scope(&["arca/".to_string()], &[]).unwrap();
|
||||||
|
v.security_record(Action::SshConnected, None, NOW + 4).unwrap();
|
||||||
|
let json = body_json(&v);
|
||||||
|
assert!(json.contains(r#""security":{"setup":{"started":"#), "{json}");
|
||||||
|
assert!(json.contains(r#""ticked":["no-ssh"]"#) && json.contains(r#""keptScope":{"ask":["arca/"]"#), "{json}");
|
||||||
|
// Core 0.11.0's parser takes it and keeps everything it knows.
|
||||||
|
let old: BodyV0_11 = serde_json::from_str(&json).unwrap();
|
||||||
|
assert_eq!(old.items.len(), 1);
|
||||||
|
assert_eq!(old.items[0].title, "kept");
|
||||||
|
// And this core reads it back the same.
|
||||||
|
let back = Vault::open(&v.to_bytes().unwrap(), &SecretString::from("pw")).unwrap();
|
||||||
|
assert_eq!(back.security_view(NOW + 5), v.security_view(NOW + 5));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_older_reader_opens_a_vault_with_the_approval_key_and_runs_but_not_approval_entries() {
|
||||||
|
use crate::signing::{Approval, Context, Request, Role, SignKind, Via};
|
||||||
|
let mut v = vault();
|
||||||
|
v.signing_create(Role::Release, &["*".to_string()], &["*".to_string()], NOW).unwrap();
|
||||||
|
let mut r = Request {
|
||||||
|
key: "domi-release".into(),
|
||||||
|
kind: SignKind::Minisign,
|
||||||
|
digest: vec![1; 64],
|
||||||
|
manifest: None,
|
||||||
|
approval: None,
|
||||||
|
run: Some("r-42".into()),
|
||||||
|
context: Context { file: "a.exe".into(), version: "0.7.0".into(), ..Default::default() },
|
||||||
|
via: Via::Local,
|
||||||
|
};
|
||||||
|
v.signing_sign(&r, Approval::Mark, NOW).unwrap();
|
||||||
|
v.provision_record(provision::ProvisionEntry {
|
||||||
|
store: provision::Store::Vault,
|
||||||
|
outcome: provision::Outcome::Accepted,
|
||||||
|
..display_entry(provision::Outcome::Accepted)
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
let json = body_json(&v);
|
||||||
|
assert!(json.contains(r#""id":"domi-approve""#) && json.contains(r#""run":"r-42""#), "{json}");
|
||||||
|
assert!(serde_json::from_str::<BodyV0_11>(&json).is_ok(), "the new key and members are ignored");
|
||||||
|
|
||||||
|
// An approval entry is a kind 0.11.0 does not know: it refuses the vault (docs/FORMAT.md).
|
||||||
|
r.key = "domi-approve".into();
|
||||||
|
r.kind = SignKind::Approval;
|
||||||
|
r.digest = vec![];
|
||||||
|
v.signing_refuse(&r, crate::signing::Outcome::Refused, None, NOW + 1);
|
||||||
|
assert!(serde_json::from_str::<BodyV0_11>(&body_json(&v)).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_older_reader_refuses_display_and_confirmed() {
|
||||||
|
for (store, outcome) in [
|
||||||
|
(provision::Store::Display, provision::Outcome::Refused),
|
||||||
|
(provision::Store::Display, provision::Outcome::Confirmed),
|
||||||
|
] {
|
||||||
|
let mut v = vault();
|
||||||
|
v.provision_record(provision::ProvisionEntry { store, ..display_entry(outcome) }).unwrap();
|
||||||
|
assert!(serde_json::from_str::<BodyV0_11>(&body_json(&v)).is_err(), "{store:?} {outcome:?}");
|
||||||
|
// This core reads it.
|
||||||
|
assert!(Vault::open(&v.to_bytes().unwrap(), &SecretString::from("pw")).is_ok());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn unknown_or_broken_security_values_make_the_vault_refuse_to_open() {
|
||||||
|
let mut v = vault();
|
||||||
|
v.security_start_setup(NOW);
|
||||||
|
v.security_tick(Item::NoSsh, NOW + 1);
|
||||||
|
v.security_untick(Item::NoSsh, Auth::Password, NOW + 2);
|
||||||
|
v.security_tick(Item::RotateSetup, NOW + 3);
|
||||||
|
v.security_keep_scope(&["arca/".to_string()], &["fabrica/".to_string()]).unwrap();
|
||||||
|
let json = body_json(&v);
|
||||||
|
// The file as written opens.
|
||||||
|
assert!(Vault::open(&with_body(&v, &json), &SecretString::from("pw")).is_ok());
|
||||||
|
let until = format!(r#""until":{}"#, NOW + SETUP_WINDOW);
|
||||||
|
let cases = [
|
||||||
|
(r#""ticked":["rotate-setup"]"#, r#""ticked":["rotate-later"]"#.to_string()),
|
||||||
|
(r#""action":"ticked""#, r#""action":"tocked""#.to_string()),
|
||||||
|
(r#""auth":"password""#, r#""auth":"pin""#.to_string()),
|
||||||
|
(r#""item":"no-ssh""#, r#""item":"no-telnet""#.to_string()),
|
||||||
|
(until.as_str(), format!(r#""until":{NOW}"#)),
|
||||||
|
(r#""ask":["arca/"]"#, r#""ask":["arca/\n"]"#.to_string()),
|
||||||
|
(r#""ask":["arca/"]"#, r#""ask":[""]"#.to_string()),
|
||||||
|
];
|
||||||
|
for (from, to) in cases {
|
||||||
|
assert!(json.contains(from), "{from} in {json}");
|
||||||
|
let bad = json.replacen(from, &to, 1);
|
||||||
|
let r = Vault::open(&with_body(&v, &bad), &SecretString::from("pw"));
|
||||||
|
assert!(matches!(r, Err(Error::Corrupted)), "{to}: {r:?}");
|
||||||
|
}
|
||||||
|
// `finished` without a window.
|
||||||
|
let mut no_window = json.clone();
|
||||||
|
let start = no_window.find(r#""setup":{"#).unwrap();
|
||||||
|
let end = start + no_window[start..].find('}').unwrap() + 2;
|
||||||
|
no_window.replace_range(start..end, r#""finished":5,"#);
|
||||||
|
let r = Vault::open(&with_body(&v, &no_window), &SecretString::from("pw"));
|
||||||
|
assert!(matches!(r, Err(Error::Corrupted)), "{no_window}");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -33,6 +33,9 @@ impl Refusal {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The key that signs deploy approvals, and nothing else (docs/SIGNING.md, "approval").
|
||||||
|
pub const APPROVE_KEY: &str = "domi-approve";
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
#[serde(rename_all = "lowercase")]
|
#[serde(rename_all = "lowercase")]
|
||||||
pub enum Role {
|
pub enum Role {
|
||||||
@@ -54,6 +57,8 @@ pub enum SignKind {
|
|||||||
Minisign,
|
Minisign,
|
||||||
Manifest,
|
Manifest,
|
||||||
Authenticode,
|
Authenticode,
|
||||||
|
/// A deploy approval's canonical JSON, signed as minisign by `domi-approve` only (core 0.12.0).
|
||||||
|
Approval,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
@@ -77,6 +82,9 @@ pub struct Context {
|
|||||||
pub file: String,
|
pub file: String,
|
||||||
pub size: u64,
|
pub size: u64,
|
||||||
pub sha256: String,
|
pub sha256: String,
|
||||||
|
/// The version being built (core 0.12.0); absent when empty, so older readers see the entry they knew.
|
||||||
|
#[serde(skip_serializing_if = "String::is_empty")]
|
||||||
|
pub version: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A signing request, from the Domi pipe or the factor service's mailbox.
|
/// A signing request, from the Domi pipe or the factor service's mailbox.
|
||||||
@@ -88,6 +96,10 @@ pub struct Request {
|
|||||||
pub digest: Vec<u8>,
|
pub digest: Vec<u8>,
|
||||||
/// The `SHA256SUMS` text, for a manifest.
|
/// The `SHA256SUMS` text, for a manifest.
|
||||||
pub manifest: Option<String>,
|
pub manifest: Option<String>,
|
||||||
|
/// The deploy approval's canonical JSON, for `SignKind::Approval` (core 0.12.0).
|
||||||
|
pub approval: Option<String>,
|
||||||
|
/// The build's run id, `[A-Za-z0-9._-]{1,64}` (core 0.12.0). Required for an approval, and equal to its `run`.
|
||||||
|
pub run: Option<String>,
|
||||||
pub context: Context,
|
pub context: Context,
|
||||||
pub via: Via,
|
pub via: Via,
|
||||||
}
|
}
|
||||||
@@ -128,6 +140,9 @@ pub struct AuditEntry {
|
|||||||
/// Why, for refusals the vault decided.
|
/// Why, for refusals the vault decided.
|
||||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
pub reason: Option<String>,
|
pub reason: Option<String>,
|
||||||
|
/// The request's run id (core 0.12.0), when it had a well-formed one.
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub run: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A signature handed back to the build.
|
/// A signature handed back to the build.
|
||||||
@@ -333,6 +348,30 @@ impl Store {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Unix seconds from the vault's milliseconds, as minisign and approvals count them.
|
||||||
|
fn seconds(now_ms: i64) -> u64 {
|
||||||
|
(now_ms.max(0) / 1000) as u64
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A new `domi-approve`: Ed25519, a release key with the given scope.
|
||||||
|
fn approve_key(pipelines: &[String], repos: &[String], now: i64) -> Key {
|
||||||
|
let ed = custos_sign::new_ed25519();
|
||||||
|
Key {
|
||||||
|
id: APPROVE_KEY.into(),
|
||||||
|
kind: KeyKind::Ed25519,
|
||||||
|
role: Role::Release,
|
||||||
|
name: "Domi deploy approval".into(),
|
||||||
|
secret: Secret::Ed25519(ed.secret),
|
||||||
|
public: Some(ed.public),
|
||||||
|
key_id: Some(ed.key_id),
|
||||||
|
cert: None,
|
||||||
|
issuer: None,
|
||||||
|
created: now,
|
||||||
|
pipelines: pipelines.to_vec(),
|
||||||
|
repos: repos.to_vec(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn in_scope(list: &[String], what: &str) -> bool {
|
fn in_scope(list: &[String], what: &str) -> bool {
|
||||||
list.iter().any(|x| x == "*" || x == what)
|
list.iter().any(|x| x == "*" || x == what)
|
||||||
}
|
}
|
||||||
@@ -419,7 +458,30 @@ impl Vault {
|
|||||||
true,
|
true,
|
||||||
);
|
);
|
||||||
self.signing.keys.extend([ed_key, root_key, leaf_key]);
|
self.signing.keys.extend([ed_key, root_key, leaf_key]);
|
||||||
Ok(vec![ed_id.into(), root_id.into(), leaf_id.into()])
|
let mut ids = vec![ed_id.to_string(), root_id.into(), leaf_id.into()];
|
||||||
|
if role == Role::Release {
|
||||||
|
self.signing.keys.push(approve_key(&pipelines, &repos, now));
|
||||||
|
ids.push(APPROVE_KEY.into());
|
||||||
|
}
|
||||||
|
Ok(ids)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Adds `domi-approve` to a vault whose release keys an older core made, with `domi-release`'s scope (else the
|
||||||
|
/// first release key's). Refused without release keys, or when the key is there already. The caller saves.
|
||||||
|
pub fn signing_add_approve(&mut self, now: i64) -> Result<String, Error> {
|
||||||
|
if self.signing.get(APPROVE_KEY).is_some() {
|
||||||
|
return Err(Error::SigningExists("approval"));
|
||||||
|
}
|
||||||
|
let release = self.signing.keys.iter().filter(|k| k.role == Role::Release && k.kind != KeyKind::RootCa);
|
||||||
|
let model = self
|
||||||
|
.signing
|
||||||
|
.get("domi-release")
|
||||||
|
.filter(|k| k.role == Role::Release)
|
||||||
|
.or_else(|| release.clone().next())
|
||||||
|
.ok_or_else(|| Error::Signing("there are no release keys to add an approval key to".into()))?;
|
||||||
|
let key = approve_key(&model.pipelines, &model.repos, now);
|
||||||
|
self.signing.keys.push(key);
|
||||||
|
Ok(APPROVE_KEY.into())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Every signing key, public parts only.
|
/// Every signing key, public parts only.
|
||||||
@@ -472,19 +534,44 @@ impl Vault {
|
|||||||
|
|
||||||
/// Whether `req` could be signed: the key exists and can do the kind, the input is well formed, the pipeline
|
/// Whether `req` could be signed: the key exists and can do the kind, the input is well formed, the pipeline
|
||||||
/// and repo are in the key's scope, and a test key is not asked for a `tag` build. Shown before any card.
|
/// and repo are in the key's scope, and a test key is not asked for a `tag` build. Shown before any card.
|
||||||
|
/// An approval's expiry is checked against the system clock; [`Vault::signing_check_at`] takes the time.
|
||||||
pub fn signing_check(&self, req: &Request) -> Result<KeyView, Refusal> {
|
pub fn signing_check(&self, req: &Request) -> Result<KeyView, Refusal> {
|
||||||
|
self.signing_check_at(req, crate::now_ms())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// [`Vault::signing_check`] at `now` (Unix milliseconds): an approval must not have expired then, and must
|
||||||
|
/// expire at most an hour later.
|
||||||
|
pub fn signing_check_at(&self, req: &Request, now: i64) -> Result<KeyView, Refusal> {
|
||||||
|
self.check(req, now).map(|(view, _)| view)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The check, and the approval it read (for an approval request).
|
||||||
|
fn check(&self, req: &Request, now: i64) -> Result<(KeyView, Option<custos_sign::Approval>), Refusal> {
|
||||||
let k = self.signing.get(&req.key).ok_or_else(|| Refusal::NoKey(req.key.clone()))?;
|
let k = self.signing.get(&req.key).ok_or_else(|| Refusal::NoKey(req.key.clone()))?;
|
||||||
let fits = matches!(
|
let approver = k.id == APPROVE_KEY && k.kind == KeyKind::Ed25519 && k.role == Role::Release;
|
||||||
(k.kind, req.kind),
|
let fits = match (k.kind, req.kind) {
|
||||||
(KeyKind::Ed25519, SignKind::Minisign | SignKind::Manifest)
|
(KeyKind::Ed25519, SignKind::Minisign | SignKind::Manifest) => k.id != APPROVE_KEY,
|
||||||
| (KeyKind::CodeSigning, SignKind::Authenticode)
|
(KeyKind::Ed25519, SignKind::Approval) => approver,
|
||||||
);
|
(KeyKind::CodeSigning, SignKind::Authenticode) => true,
|
||||||
|
_ => false,
|
||||||
|
};
|
||||||
if k.kind == KeyKind::RootCa {
|
if k.kind == KeyKind::RootCa {
|
||||||
return Err(Refusal::Invalid(format!("`{}` is a root CA: it signs only the certificate it issued", k.id)));
|
return Err(Refusal::Invalid(format!("`{}` is a root CA: it signs only the certificate it issued", k.id)));
|
||||||
}
|
}
|
||||||
if !fits {
|
if !fits {
|
||||||
return Err(Refusal::Invalid(format!("`{}` cannot make {:?} signatures", k.id, req.kind)));
|
return Err(Refusal::Invalid(if k.id == APPROVE_KEY || req.kind == SignKind::Approval {
|
||||||
|
format!("`{APPROVE_KEY}` signs deploy approvals only, and only it signs them (asked: `{}`)", k.id)
|
||||||
|
} else {
|
||||||
|
format!("`{}` cannot make {:?} signatures", k.id, req.kind)
|
||||||
|
}));
|
||||||
}
|
}
|
||||||
|
if req.run.as_deref().is_some_and(|r| !custos_sign::run_id_ok(r)) {
|
||||||
|
return Err(Refusal::Invalid("the run is not a run id ([A-Za-z0-9._-], 1 to 64)".into()));
|
||||||
|
}
|
||||||
|
if req.kind != SignKind::Approval && req.approval.is_some() {
|
||||||
|
return Err(Refusal::Invalid("approval text comes only with an approval request".into()));
|
||||||
|
}
|
||||||
|
let mut approval = None;
|
||||||
match req.kind {
|
match req.kind {
|
||||||
SignKind::Minisign if req.digest.len() != 64 => {
|
SignKind::Minisign if req.digest.len() != 64 => {
|
||||||
return Err(Refusal::Invalid("a minisign digest is BLAKE2b-512: 64 bytes".into()));
|
return Err(Refusal::Invalid("a minisign digest is BLAKE2b-512: 64 bytes".into()));
|
||||||
@@ -496,31 +583,56 @@ impl Vault {
|
|||||||
let text = req.manifest.as_deref().ok_or_else(|| Refusal::Invalid("no manifest text".into()))?;
|
let text = req.manifest.as_deref().ok_or_else(|| Refusal::Invalid("no manifest text".into()))?;
|
||||||
custos_sign::manifest_check(text).map_err(|e| Refusal::Invalid(e.to_string()))?;
|
custos_sign::manifest_check(text).map_err(|e| Refusal::Invalid(e.to_string()))?;
|
||||||
}
|
}
|
||||||
|
SignKind::Approval => {
|
||||||
|
let text = req.approval.as_deref().ok_or_else(|| Refusal::Invalid("no approval text".into()))?;
|
||||||
|
let a = custos_sign::approval_check(text, seconds(now)).map_err(|e| Refusal::Invalid(e.to_string()))?;
|
||||||
|
if req.run.as_deref() != Some(a.run.as_str()) {
|
||||||
|
return Err(Refusal::Invalid("the approval's run is not the request's run".into()));
|
||||||
|
}
|
||||||
|
let c = &req.context;
|
||||||
|
for (member, ours, theirs) in [
|
||||||
|
("repo", &c.repo, &a.repo),
|
||||||
|
("pipeline", &c.pipeline, &a.pipeline),
|
||||||
|
("commit", &c.commit, &a.commit),
|
||||||
|
("version", &c.version, &a.version),
|
||||||
|
] {
|
||||||
|
if !ours.is_empty() && ours != theirs {
|
||||||
|
return Err(Refusal::Invalid(format!("the request's {member} is not the approval's")));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
approval = Some(a);
|
||||||
|
}
|
||||||
_ => {}
|
_ => {}
|
||||||
}
|
}
|
||||||
let file = &req.context.file;
|
let file = &req.context.file;
|
||||||
if req.kind != SignKind::Manifest
|
if !matches!(req.kind, SignKind::Manifest | SignKind::Approval)
|
||||||
&& (file.is_empty() || file.len() > 255 || file.contains(['/', '\\']) || file.chars().any(char::is_control))
|
&& (file.is_empty() || file.len() > 255 || file.contains(['/', '\\']) || file.chars().any(char::is_control))
|
||||||
{
|
{
|
||||||
return Err(Refusal::Invalid("the file name is missing or not a plain name".into()));
|
return Err(Refusal::Invalid("the file name is missing or not a plain name".into()));
|
||||||
}
|
}
|
||||||
if !in_scope(&k.pipelines, &req.context.pipeline) {
|
// An approval is scoped by what it approves.
|
||||||
return Err(Refusal::OutOfScope(format!("pipeline `{}` may not use `{}`", req.context.pipeline, k.id)));
|
let (pipeline, repo) = match &approval {
|
||||||
|
Some(a) => (a.pipeline.as_str(), a.repo.as_str()),
|
||||||
|
None => (req.context.pipeline.as_str(), req.context.repo.as_str()),
|
||||||
|
};
|
||||||
|
if !in_scope(&k.pipelines, pipeline) {
|
||||||
|
return Err(Refusal::OutOfScope(format!("pipeline `{pipeline}` may not use `{}`", k.id)));
|
||||||
}
|
}
|
||||||
if !in_scope(&k.repos, &req.context.repo) {
|
if !in_scope(&k.repos, repo) {
|
||||||
return Err(Refusal::OutOfScope(format!("repo `{}` may not use `{}`", req.context.repo, k.id)));
|
return Err(Refusal::OutOfScope(format!("repo `{repo}` may not use `{}`", k.id)));
|
||||||
}
|
}
|
||||||
if k.role == Role::Test && req.context.trigger == "tag" {
|
if k.role == Role::Test && req.context.trigger == "tag" {
|
||||||
return Err(Refusal::OutOfScope(format!("`{}` is a test key: it never signs a tag (release) build", k.id)));
|
return Err(Refusal::OutOfScope(format!("`{}` is a test key: it never signs a tag (release) build", k.id)));
|
||||||
}
|
}
|
||||||
Ok(self.signing_keys().into_iter().find(|v| v.id == k.id).expect("the key exists"))
|
let view = self.signing_keys().into_iter().find(|v| v.id == k.id).expect("the key exists");
|
||||||
|
Ok((view, approval))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Checks `req` again and signs it, recording the outcome. `Approval::Auto` works for test keys only.
|
/// Checks `req` again and signs it, recording the outcome. `Approval::Auto` works for test keys only.
|
||||||
/// A refusal is recorded too. The caller saves.
|
/// A refusal is recorded too. The caller saves.
|
||||||
pub fn signing_sign(&mut self, req: &Request, approval: Approval, now: i64) -> Result<Signed, Refusal> {
|
pub fn signing_sign(&mut self, req: &Request, approval: Approval, now: i64) -> Result<Signed, Refusal> {
|
||||||
let view = match self.signing_check(req) {
|
let view = match self.check(req, now) {
|
||||||
Ok(v) => v,
|
Ok((v, _)) => v,
|
||||||
Err(r) => {
|
Err(r) => {
|
||||||
self.signing_record(req, r.outcome(), Some(r.to_string()), None, now);
|
self.signing_record(req, r.outcome(), Some(r.to_string()), None, now);
|
||||||
return Err(r);
|
return Err(r);
|
||||||
@@ -532,7 +644,7 @@ impl Vault {
|
|||||||
return Err(r);
|
return Err(r);
|
||||||
}
|
}
|
||||||
let k = self.signing.get(&req.key).expect("checked");
|
let k = self.signing.get(&req.key).expect("checked");
|
||||||
let seconds = (now.max(0) / 1000) as u64;
|
let seconds = seconds(now);
|
||||||
let bytes = match (&k.secret, req.kind) {
|
let bytes = match (&k.secret, req.kind) {
|
||||||
(Secret::Ed25519(s), SignKind::Minisign) => custos_sign::minisign(
|
(Secret::Ed25519(s), SignKind::Minisign) => custos_sign::minisign(
|
||||||
s,
|
s,
|
||||||
@@ -549,6 +661,14 @@ impl Vault {
|
|||||||
seconds,
|
seconds,
|
||||||
)
|
)
|
||||||
.map(String::into_bytes),
|
.map(String::into_bytes),
|
||||||
|
(Secret::Ed25519(s), SignKind::Approval) => custos_sign::approval(
|
||||||
|
s,
|
||||||
|
&k.key_id.expect("ed25519 keys have an id"),
|
||||||
|
req.approval.as_deref().unwrap_or_default(),
|
||||||
|
seconds,
|
||||||
|
req.run.as_deref().unwrap_or_default(),
|
||||||
|
)
|
||||||
|
.map(String::into_bytes),
|
||||||
(Secret::Rsa(s), SignKind::Authenticode) => custos_sign::authenticode(s, &req.digest),
|
(Secret::Rsa(s), SignKind::Authenticode) => custos_sign::authenticode(s, &req.digest),
|
||||||
_ => unreachable!("signing_check matched the key to the kind"),
|
_ => unreachable!("signing_check matched the key to the kind"),
|
||||||
};
|
};
|
||||||
@@ -584,8 +704,31 @@ impl Vault {
|
|||||||
now: i64,
|
now: i64,
|
||||||
) {
|
) {
|
||||||
let mut context = req.context.clone();
|
let mut context = req.context.clone();
|
||||||
if req.kind == SignKind::Manifest {
|
let run = req.run.clone().filter(|r| custos_sign::run_id_ok(r));
|
||||||
context.file = "SHA256SUMS".into();
|
match req.kind {
|
||||||
|
SignKind::Manifest => context.file = "SHA256SUMS".into(),
|
||||||
|
SignKind::Approval => {
|
||||||
|
context.file = match &run {
|
||||||
|
Some(r) => format!("approval-{r}.json"),
|
||||||
|
None => "approval.json".into(),
|
||||||
|
};
|
||||||
|
// What the approval says, where the request left the context empty: read without the clock, so a
|
||||||
|
// refused or expired request is filled in too. A text that does not read leaves the context as is.
|
||||||
|
let read = custos_sign::approval_parse(req.approval.as_deref().unwrap_or_default()).ok();
|
||||||
|
if let Some(a) = read {
|
||||||
|
for (ours, theirs) in [
|
||||||
|
(&mut context.repo, a.repo),
|
||||||
|
(&mut context.pipeline, a.pipeline),
|
||||||
|
(&mut context.commit, a.commit),
|
||||||
|
(&mut context.version, a.version),
|
||||||
|
] {
|
||||||
|
if ours.is_empty() {
|
||||||
|
*ours = theirs;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
}
|
}
|
||||||
self.signing.audit.push(AuditEntry {
|
self.signing.audit.push(AuditEntry {
|
||||||
at: now,
|
at: now,
|
||||||
@@ -596,6 +739,7 @@ impl Vault {
|
|||||||
context,
|
context,
|
||||||
signature,
|
signature,
|
||||||
reason,
|
reason,
|
||||||
|
run,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -622,6 +766,8 @@ mod tests {
|
|||||||
kind,
|
kind,
|
||||||
digest: vec![5; digest],
|
digest: vec![5; digest],
|
||||||
manifest: None,
|
manifest: None,
|
||||||
|
approval: None,
|
||||||
|
run: None,
|
||||||
context: Context {
|
context: Context {
|
||||||
repo: "Arca".into(),
|
repo: "Arca".into(),
|
||||||
pipeline: "release".into(),
|
pipeline: "release".into(),
|
||||||
@@ -633,6 +779,26 @@ mod tests {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_vault_with_release_keys_from_an_older_core_gets_its_approval_key() {
|
||||||
|
let mut v =
|
||||||
|
Vault::create(&SecretString::from("pw"), KdfParams { m_cost_kib: 64, t_cost: 1, p_cost: 1 }).unwrap();
|
||||||
|
v.signing_create(Role::Release, &s(&["release"]), &s(&["Arca"]), 1).unwrap();
|
||||||
|
// What core 0.11.0 made: the release set without `domi-approve`.
|
||||||
|
v.signing.keys.retain(|k| k.id != "domi-approve");
|
||||||
|
assert_eq!(v.signing.keys.len(), 3);
|
||||||
|
assert_eq!(v.signing_add_approve(7).unwrap(), "domi-approve");
|
||||||
|
let views = v.signing_keys();
|
||||||
|
let a = views.iter().find(|k| k.id == "domi-approve").unwrap();
|
||||||
|
assert_eq!((a.kind, a.role, a.created), (KeyKind::Ed25519, Role::Release, 7));
|
||||||
|
assert_eq!((a.pipelines.clone(), a.repos.clone()), (s(&["release"]), s(&["Arca"])));
|
||||||
|
assert!(a.minisign_public.is_some());
|
||||||
|
assert!(matches!(v.signing_add_approve(8), Err(Error::SigningExists("approval"))));
|
||||||
|
// It survives a save and a reopen.
|
||||||
|
let back = Vault::open(&v.to_bytes().unwrap(), &SecretString::from("pw")).unwrap();
|
||||||
|
assert_eq!(back.signing_keys(), views);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn no_api_path_returns_a_private_key() {
|
fn no_api_path_returns_a_private_key() {
|
||||||
let mut v =
|
let mut v =
|
||||||
@@ -648,7 +814,7 @@ mod tests {
|
|||||||
Secret::Rsa(s) => s.expose().to_vec(),
|
Secret::Rsa(s) => s.expose().to_vec(),
|
||||||
})
|
})
|
||||||
.collect();
|
.collect();
|
||||||
assert_eq!(secrets.len(), 6);
|
assert_eq!(secrets.len(), 7, "the release set with domi-approve, and the test set");
|
||||||
|
|
||||||
// Every public way out: views (serialised and printed), certificates, minisign public keys, checks,
|
// Every public way out: views (serialised and printed), certificates, minisign public keys, checks,
|
||||||
// signatures of every kind, refusals, the audit log, errors, and the Debug of the vault's own store.
|
// signatures of every kind, refusals, the audit log, errors, and the Debug of the vault's own store.
|
||||||
@@ -665,6 +831,14 @@ mod tests {
|
|||||||
vec![req("domi-release", SignKind::Minisign, 64), req("domi-code-signing", SignKind::Authenticode, 32)];
|
vec![req("domi-release", SignKind::Minisign, 64), req("domi-code-signing", SignKind::Authenticode, 32)];
|
||||||
reqs.push(req("domi-root", SignKind::Authenticode, 32));
|
reqs.push(req("domi-root", SignKind::Authenticode, 32));
|
||||||
reqs.push(req("domi-test", SignKind::Minisign, 64));
|
reqs.push(req("domi-test", SignKind::Minisign, 64));
|
||||||
|
let mut approve = req("domi-approve", SignKind::Approval, 0);
|
||||||
|
approve.run = Some("r-1".into());
|
||||||
|
approve.approval = Some(format!(
|
||||||
|
r#"{{"v":1,"run":"r-1","repo":"Arca","commit":"{}","pipeline":"release","version":"1.0.0","targets":["deploy"],"expires":600}}"#,
|
||||||
|
"a".repeat(40)
|
||||||
|
));
|
||||||
|
reqs.push(approve);
|
||||||
|
reqs.push(req("domi-approve", SignKind::Minisign, 64));
|
||||||
for r in &reqs {
|
for r in &reqs {
|
||||||
out += &format!("{:?}", v.signing_check(r));
|
out += &format!("{:?}", v.signing_check(r));
|
||||||
for approval in [Approval::Mark, Approval::Auto] {
|
for approval in [Approval::Mark, Approval::Auto] {
|
||||||
@@ -674,6 +848,10 @@ mod tests {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
assert!(
|
||||||
|
v.signing_audit().iter().any(|e| e.kind == SignKind::Approval && e.outcome == Outcome::Approved),
|
||||||
|
"an approval was signed too"
|
||||||
|
);
|
||||||
out += &serde_json::to_string(v.signing_audit()).unwrap();
|
out += &serde_json::to_string(v.signing_audit()).unwrap();
|
||||||
out += &format!("{:?}", v.signing_audit());
|
out += &format!("{:?}", v.signing_audit());
|
||||||
out += &format!("{:?}", v.signing_create(Role::Release, &[], &[], 3));
|
out += &format!("{:?}", v.signing_create(Role::Release, &[], &[], 3));
|
||||||
|
|||||||
@@ -128,6 +128,8 @@ fn the_identity_survives_saving_in_both_versions() {
|
|||||||
not_before: 1,
|
not_before: 1,
|
||||||
not_after: 2,
|
not_after: 2,
|
||||||
issued: 3,
|
issued: 3,
|
||||||
|
revoked_at: Some(4),
|
||||||
|
revocation: vec!["VFJWMQ".into()],
|
||||||
};
|
};
|
||||||
// Version 1.
|
// Version 1.
|
||||||
let mut v = vault();
|
let mut v = vault();
|
||||||
@@ -165,8 +167,176 @@ fn a_record_needs_an_identity() {
|
|||||||
not_before: 0,
|
not_before: 0,
|
||||||
not_after: 1,
|
not_after: 1,
|
||||||
issued: 0,
|
issued: 0,
|
||||||
|
..Issued::default()
|
||||||
};
|
};
|
||||||
assert!(matches!(v.domi_record(i), Err(Error::NoIdentity)));
|
assert!(matches!(v.domi_record(i), Err(Error::NoIdentity)));
|
||||||
|
assert!(matches!(v.domi_mark_revoked("x", 1), Err(Error::NoIdentity)));
|
||||||
|
assert!(matches!(v.domi_backup_secret("fiscus"), Err(Error::NoIdentity)));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- v1.1: restoring, revoking, the backup secret (docs/IDENTITY.md) ----
|
||||||
|
|
||||||
|
const ZERO_PHRASE: &str = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon \
|
||||||
|
abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon \
|
||||||
|
abandon art";
|
||||||
|
const REVOKE_DOMAIN: &[u8] = b"tessera revoke v1\0";
|
||||||
|
const SUBKEY_9: &str = "CQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQk"; // [9; 32]
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_24_words_restore_the_same_root() {
|
||||||
|
let mut v = vault();
|
||||||
|
Enrollment::restore(ZERO_PHRASE).unwrap().import(&mut v).unwrap();
|
||||||
|
assert_eq!(v.domi_root_public().unwrap().to_vec(), b64url(ROOT_PUB_ZERO));
|
||||||
|
// Any case, any spacing, as long as the words are right.
|
||||||
|
let mut w = vault();
|
||||||
|
let messy = format!(" {}\n", ZERO_PHRASE.to_uppercase().replace(' ', " \t"));
|
||||||
|
Enrollment::restore(&messy).unwrap().import(&mut w).unwrap();
|
||||||
|
assert_eq!(w.domi_root_public(), v.domi_root_public());
|
||||||
|
// And from words that were shown: the same root as enrolling.
|
||||||
|
let mut e = vault();
|
||||||
|
let words = enrol(&mut e, [42; 32]);
|
||||||
|
let mut r = vault();
|
||||||
|
Enrollment::restore(&words.join(" ")).unwrap().import(&mut r).unwrap();
|
||||||
|
assert_eq!(r.domi_root_public(), e.domi_root_public());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_wrong_phrase_restores_nothing_and_names_no_word() {
|
||||||
|
let bad_checksum = ZERO_PHRASE.replace("art", "abandon");
|
||||||
|
let short = "abandon ".repeat(11) + "about";
|
||||||
|
let typo = ZERO_PHRASE.replacen("abandon", "abandn", 1);
|
||||||
|
for phrase in [bad_checksum.as_str(), short.as_str(), typo.as_str(), "", "art"] {
|
||||||
|
let e = Enrollment::restore(phrase).map(|_| ()).unwrap_err();
|
||||||
|
assert!(matches!(e, Error::NotAMnemonic), "{phrase}");
|
||||||
|
let shown = format!("{e} {e:?}");
|
||||||
|
assert!(!shown.contains("abandon") && !shown.contains("art "), "{shown}");
|
||||||
|
}
|
||||||
|
// Into a vault that has one already: refused, the old one stays.
|
||||||
|
let mut v = vault();
|
||||||
|
enrol(&mut v, [5; 32]);
|
||||||
|
let before = v.domi_root_public();
|
||||||
|
assert!(matches!(Enrollment::restore(ZERO_PHRASE).unwrap().import(&mut v), Err(Error::IdentityExists)));
|
||||||
|
assert_eq!(v.domi_root_public(), before);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A revocation's to-be-signed bytes as tessera makes them: TRV1 ‖ root ‖ subkey ‖ revoked_at ‖ part ‖
|
||||||
|
/// parts ‖ count ‖ hashes.
|
||||||
|
fn trv1(root: &[u8; 32], subkey: &[u8; 32], revoked_at: u64) -> Vec<u8> {
|
||||||
|
let mut t = b"TRV1".to_vec();
|
||||||
|
t.extend_from_slice(root);
|
||||||
|
t.extend_from_slice(subkey);
|
||||||
|
t.extend_from_slice(&revoked_at.to_be_bytes());
|
||||||
|
t.extend_from_slice(&0u16.to_be_bytes());
|
||||||
|
t.extend_from_slice(&1u16.to_be_bytes());
|
||||||
|
t.extend_from_slice(&1u32.to_be_bytes());
|
||||||
|
t.extend_from_slice(&[7; 32]);
|
||||||
|
t
|
||||||
|
}
|
||||||
|
|
||||||
|
fn issued_to(subkey: &str, app_id: &str) -> Issued {
|
||||||
|
Issued {
|
||||||
|
kind: "app".into(),
|
||||||
|
app_id: app_id.into(),
|
||||||
|
purpose: "sync".into(),
|
||||||
|
subkey: subkey.into(),
|
||||||
|
label: "fiscus.exe".into(),
|
||||||
|
not_before: 1,
|
||||||
|
not_after: 2,
|
||||||
|
issued: 3,
|
||||||
|
..Issued::default()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_root_signs_a_revocation_only_for_a_key_the_person_revoked() {
|
||||||
|
let mut v = vault();
|
||||||
|
enrol(&mut v, [0; 32]);
|
||||||
|
let root = v.domi_root_public().unwrap();
|
||||||
|
v.domi_record(issued_to(SUBKEY_9, "fiscus")).unwrap();
|
||||||
|
// Issued, but not revoked yet: refused.
|
||||||
|
let t = trv1(&root, &[9; 32], 1000);
|
||||||
|
assert!(matches!(v.domi_sign_revocation(&t), Err(Error::NotARevocation)));
|
||||||
|
// An unknown key cannot be marked.
|
||||||
|
assert!(matches!(v.domi_mark_revoked("CgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgo", 1000), Err(Error::UnknownKey)));
|
||||||
|
|
||||||
|
// A renewal issued a second cert for the same key: marking covers both, and the first time stays.
|
||||||
|
v.domi_record(issued_to(SUBKEY_9, "fiscus")).unwrap();
|
||||||
|
assert_eq!(v.domi_mark_revoked(SUBKEY_9, 1000).unwrap(), 1000);
|
||||||
|
assert_eq!(v.domi_mark_revoked(SUBKEY_9, 2000).unwrap(), 1000, "the first revocation time stays");
|
||||||
|
assert!(v.domi_issued().iter().all(|i| i.revoked_at == Some(1000)));
|
||||||
|
|
||||||
|
let sig = v.domi_sign_revocation(&t).unwrap();
|
||||||
|
let vk = VerifyingKey::from_bytes(&root).unwrap();
|
||||||
|
vk.verify_strict(&[REVOKE_DOMAIN, &t].concat(), &Signature::from_bytes(&sig)).unwrap();
|
||||||
|
assert!(
|
||||||
|
vk.verify_strict(&[CERT_DOMAIN, &t].concat(), &Signature::from_bytes(&sig)).is_err(),
|
||||||
|
"not a cert signature"
|
||||||
|
);
|
||||||
|
|
||||||
|
// Another time, another key, another root, a cert, garbage, the bare prefix: refused.
|
||||||
|
for bad in [
|
||||||
|
trv1(&root, &[9; 32], 999),
|
||||||
|
trv1(&root, &[10; 32], 1000),
|
||||||
|
trv1(&[1; 32], &[9; 32], 1000),
|
||||||
|
tbs(&root),
|
||||||
|
b"pay 100 CZK to mallory".to_vec(),
|
||||||
|
t[..76].to_vec(),
|
||||||
|
] {
|
||||||
|
assert!(matches!(v.domi_sign_revocation(&bad), Err(Error::NotARevocation)), "{bad:?}");
|
||||||
|
}
|
||||||
|
// And the cert signer never signs a revocation.
|
||||||
|
assert!(matches!(v.domi_sign_cert(&t), Err(Error::NotACert)));
|
||||||
|
|
||||||
|
// The statements are kept with every cert of the key, and survive a save.
|
||||||
|
v.domi_record_revocation(SUBKEY_9, vec!["first".into(), "second".into()]).unwrap();
|
||||||
|
assert!(matches!(
|
||||||
|
v.domi_record_revocation("CgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgo", vec![]),
|
||||||
|
Err(Error::UnknownKey)
|
||||||
|
));
|
||||||
|
let back = Vault::open(&v.to_bytes().unwrap(), &SecretString::from("pw")).unwrap();
|
||||||
|
assert!(back.domi_issued().iter().all(|i| i.revoked_at == Some(1000) && i.revocation == ["first", "second"]));
|
||||||
|
assert_eq!(back.domi_sign_revocation(&t).unwrap(), sig);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_cert_without_a_revocation_is_saved_as_before() {
|
||||||
|
let mut v = vault();
|
||||||
|
enrol(&mut v, [0; 32]);
|
||||||
|
v.domi_record(issued_to(SUBKEY_9, "fiscus")).unwrap();
|
||||||
|
let json = serde_json::to_string(&v.domi_issued()[0]).unwrap();
|
||||||
|
assert!(!json.contains("revoked_at") && !json.contains("revocation"), "{json}");
|
||||||
|
// And a record from core 0.7.0, without the two members, reads.
|
||||||
|
let old: Issued = serde_json::from_str(
|
||||||
|
r#"{"kind":"app","app_id":"fiscus","purpose":"sync","subkey":"x","label":"l","not_before":1,"not_after":2,"issued":3}"#,
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!((old.revoked_at, old.revocation.len()), (None, 0));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_backup_secret_matches_fundamentum() {
|
||||||
|
use chacha20poly1305::aead::{Aead, KeyInit, Payload};
|
||||||
|
let mut v = vault();
|
||||||
|
enrol(&mut v, [0; 32]);
|
||||||
|
let secret = v.domi_backup_secret("fiscus").unwrap();
|
||||||
|
let expand = |info: &[u8]| {
|
||||||
|
let mut out = [0u8; 32];
|
||||||
|
hkdf::Hkdf::<sha2::Sha256>::from_prk(secret.as_ref()).unwrap().expand(info, &mut out).unwrap();
|
||||||
|
out
|
||||||
|
};
|
||||||
|
// Fundamentum docs/TESSERA.md §12.
|
||||||
|
assert_eq!(expand(b"mailbox").to_vec(), b64url("IygCOrh-ibO6-KY5AXQ9Prl2SyPWQIyZZ-anffcbMCU"));
|
||||||
|
let key = expand(b"seal");
|
||||||
|
let tag = chacha20poly1305::XChaCha20Poly1305::new_from_slice(&key)
|
||||||
|
.unwrap()
|
||||||
|
.encrypt(&chacha20poly1305::XNonce::try_from(&[0u8; 24][..]).unwrap(), Payload { msg: b"", aad: b"" })
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(tag, b64url("ci_JRbtsx5prR83KT9Y7LA"));
|
||||||
|
// One per app, the same from the restored words.
|
||||||
|
assert_ne!(*v.domi_backup_secret("calenda").unwrap(), *secret);
|
||||||
|
let mut r = vault();
|
||||||
|
Enrollment::restore(ZERO_PHRASE).unwrap().import(&mut r).unwrap();
|
||||||
|
assert_eq!(*r.domi_backup_secret("fiscus").unwrap(), *secret);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -206,13 +376,19 @@ fn the_identity_surface_is_locked() {
|
|||||||
"identity.rs: pub fn challenge(&self) -> [usize; 3]",
|
"identity.rs: pub fn challenge(&self) -> [usize; 3]",
|
||||||
"identity.rs: pub fn confirm(self, words: &[&str; 3]) -> Result<Confirmed, (Shown, Error)>",
|
"identity.rs: pub fn confirm(self, words: &[&str; 3]) -> Result<Confirmed, (Shown, Error)>",
|
||||||
"identity.rs: pub fn import(self, vault: &mut Vault) -> Result<[u8; 32], Error>",
|
"identity.rs: pub fn import(self, vault: &mut Vault) -> Result<[u8; 32], Error>",
|
||||||
|
"identity.rs: pub fn restore(phrase: &str) -> Result<Confirmed, Error>",
|
||||||
"identity.rs: pub fn show(self, display: impl FnOnce(&[&str])) -> Shown",
|
"identity.rs: pub fn show(self, display: impl FnOnce(&[&str])) -> Shown",
|
||||||
"identity.rs: pub fn with_entropy(entropy: [u8; 32]) -> Enrollment",
|
"identity.rs: pub fn with_entropy(entropy: [u8; 32]) -> Enrollment",
|
||||||
|
// The app's own backup secret, derived: by design (docs/IDENTITY.md), never the root.
|
||||||
|
"lib.rs: pub fn domi_backup_secret(&self, app_id: &str) -> Result<Zeroizing<[u8; 32]>, Error>",
|
||||||
"lib.rs: pub fn domi_created(&self) -> Option<i64>",
|
"lib.rs: pub fn domi_created(&self) -> Option<i64>",
|
||||||
"lib.rs: pub fn domi_issued(&self) -> &[identity::Issued]",
|
"lib.rs: pub fn domi_issued(&self) -> &[identity::Issued]",
|
||||||
|
"lib.rs: pub fn domi_mark_revoked(&mut self, subkey: &str, revoked_at: u64) -> Result<u64, Error>",
|
||||||
"lib.rs: pub fn domi_record(&mut self, issued: identity::Issued) -> Result<(), Error>",
|
"lib.rs: pub fn domi_record(&mut self, issued: identity::Issued) -> Result<(), Error>",
|
||||||
|
"lib.rs: pub fn domi_record_revocation(&mut self, subkey: &str, statements: Vec<String>) -> Result<(), Error>",
|
||||||
"lib.rs: pub fn domi_root_public(&self) -> Option<[u8; 32]>",
|
"lib.rs: pub fn domi_root_public(&self) -> Option<[u8; 32]>",
|
||||||
"lib.rs: pub fn domi_sign_cert(&self, tbs: &[u8]) -> Result<[u8; 64], Error>",
|
"lib.rs: pub fn domi_sign_cert(&self, tbs: &[u8]) -> Result<[u8; 64], Error>",
|
||||||
|
"lib.rs: pub fn domi_sign_revocation(&self, tbs: &[u8]) -> Result<[u8; 64], Error>",
|
||||||
];
|
];
|
||||||
want.sort();
|
want.sort();
|
||||||
assert_eq!(got, want, "review the identity surface: it must never return the root secret");
|
assert_eq!(got, want, "review the identity surface: it must never return the root secret");
|
||||||
|
|||||||
@@ -0,0 +1,210 @@
|
|||||||
|
//! Mandatory tests for the Provisio audit (docs/FORMAT.md, "The provision audit"): it survives a reopen, takes
|
||||||
|
//! only entries that fit, is append-only and bounded, and has no member that could hold a secret. That an older
|
||||||
|
//! reader still opens such a vault is a unit test in src/provision.rs, which can see the decrypted body.
|
||||||
|
|
||||||
|
use custos_vault::provision::{AUDIT_LIMIT, Direction, Outcome, ProvisionEntry, Store};
|
||||||
|
use custos_vault::{Error, KdfParams, SecretString, Vault};
|
||||||
|
|
||||||
|
const FAST: KdfParams = KdfParams { m_cost_kib: 64, t_cost: 1, p_cost: 1 };
|
||||||
|
const NOW: i64 = 1_793_750_000_000;
|
||||||
|
|
||||||
|
/// One way to spoil an entry.
|
||||||
|
type Change = Box<dyn Fn(&mut ProvisionEntry)>;
|
||||||
|
|
||||||
|
fn entry(i: i64, outcome: Outcome) -> ProvisionEntry {
|
||||||
|
ProvisionEntry {
|
||||||
|
at: NOW + i,
|
||||||
|
direction: Direction::Offer,
|
||||||
|
host: "nixos-vm".into(),
|
||||||
|
item: "fabrica/gitea-read-token".into(),
|
||||||
|
store: Store::Vault,
|
||||||
|
run: Some("deploy-7".into()),
|
||||||
|
kind: Some("Gitea token, read:repository".into()),
|
||||||
|
code: "684361".into(),
|
||||||
|
outcome,
|
||||||
|
replaced: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_provision_audit_records_every_outcome_and_survives_a_reopen() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let path = dir.path().join("v.custos");
|
||||||
|
let mut v = Vault::create(&SecretString::from("pw"), FAST).unwrap();
|
||||||
|
assert!(v.provision_audit().is_empty());
|
||||||
|
let all = [
|
||||||
|
Outcome::Approved,
|
||||||
|
Outcome::Generated,
|
||||||
|
Outcome::Accepted,
|
||||||
|
Outcome::Refused,
|
||||||
|
Outcome::OutOfScope,
|
||||||
|
Outcome::Invalid,
|
||||||
|
Outcome::Expired,
|
||||||
|
];
|
||||||
|
for (i, o) in all.iter().enumerate() {
|
||||||
|
let mut e = entry(i as i64, *o);
|
||||||
|
if i % 2 == 0 {
|
||||||
|
e.direction = Direction::Ask;
|
||||||
|
e.store = Store::Vault;
|
||||||
|
e.kind = None;
|
||||||
|
e.run = None;
|
||||||
|
} else {
|
||||||
|
e.store = if i % 3 == 0 { Store::Claude } else { Store::Cloud };
|
||||||
|
e.item = "fabrica-hub-token".into();
|
||||||
|
}
|
||||||
|
e.replaced = *o == Outcome::Accepted;
|
||||||
|
v.provision_record(e).unwrap();
|
||||||
|
}
|
||||||
|
v.save(&path).unwrap();
|
||||||
|
|
||||||
|
let back = Vault::open_file(&path, &SecretString::from("pw")).unwrap();
|
||||||
|
let audit: &[ProvisionEntry] = back.provision_audit();
|
||||||
|
assert_eq!(audit, v.provision_audit());
|
||||||
|
assert_eq!(audit.iter().map(|e| e.outcome).collect::<Vec<_>>(), all);
|
||||||
|
// Newest last.
|
||||||
|
assert!(audit.windows(2).all(|w| w[0].at < w[1].at));
|
||||||
|
assert_eq!(audit[0].direction, Direction::Ask);
|
||||||
|
assert_eq!(audit[1].store, Store::Cloud);
|
||||||
|
assert_eq!(audit[3].store, Store::Claude);
|
||||||
|
assert!(audit[2].replaced && !audit[1].replaced);
|
||||||
|
// The signing audit is a separate log and stays empty.
|
||||||
|
assert!(back.signing_audit().is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn entries_that_do_not_fit_are_refused_and_not_stored() {
|
||||||
|
let mut v = Vault::create(&SecretString::from("pw"), FAST).unwrap();
|
||||||
|
v.provision_record(entry(0, Outcome::Approved)).unwrap();
|
||||||
|
let secretish = "ghp_s3cr3tV4lu3ThatMustNeverBeInAnError";
|
||||||
|
let bad: Vec<Change> = vec![
|
||||||
|
Box::new(|e| e.code = "68436".into()),
|
||||||
|
Box::new(|e| e.code = "68436a".into()),
|
||||||
|
Box::new(|e| e.code = "6843611".into()),
|
||||||
|
Box::new(|e| e.item = "Arca/x".into()),
|
||||||
|
Box::new(|e| e.item = "../x".into()),
|
||||||
|
Box::new(|e| e.item = "a/b/c/d/e".into()),
|
||||||
|
Box::new(|e| e.item = String::new()),
|
||||||
|
Box::new(|e| e.item = format!("arca/{}", "x".repeat(65))),
|
||||||
|
Box::new(|e| e.run = Some(String::new())),
|
||||||
|
Box::new(|e| e.run = Some("run 1".into())),
|
||||||
|
Box::new(|e| e.run = Some("r".repeat(65))),
|
||||||
|
Box::new(|e| e.host = String::new()),
|
||||||
|
Box::new(|e| e.host = "nixos vm".into()),
|
||||||
|
Box::new(|e| e.host = "h".repeat(254)),
|
||||||
|
Box::new(|e| e.kind = Some("x".repeat(201))),
|
||||||
|
Box::new(move |e| e.kind = Some(format!("token\n{secretish}"))),
|
||||||
|
];
|
||||||
|
for (i, change) in bad.iter().enumerate() {
|
||||||
|
let mut e = entry(1, Outcome::Accepted);
|
||||||
|
change(&mut e);
|
||||||
|
let err = v.provision_record(e).unwrap_err();
|
||||||
|
assert!(matches!(err, Error::Provision(_)), "case {i}: {err:?}");
|
||||||
|
assert!(!format!("{err}{err:?}").contains(secretish), "case {i}: an error repeats a value");
|
||||||
|
}
|
||||||
|
assert_eq!(v.provision_audit(), [entry(0, Outcome::Approved)]);
|
||||||
|
// The limits themselves fit.
|
||||||
|
let mut e = entry(2, Outcome::Accepted);
|
||||||
|
e.item = format!("a{0}/b{0}/c{0}/d{0}", "x".repeat(63));
|
||||||
|
e.run = Some("R".repeat(64));
|
||||||
|
e.host = "h".repeat(253);
|
||||||
|
e.kind = Some("k".repeat(200));
|
||||||
|
v.provision_record(e).unwrap();
|
||||||
|
assert_eq!(v.provision_audit().len(), 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_audit_is_append_only_and_keeps_the_newest_entries() {
|
||||||
|
let mut v = Vault::create(&SecretString::from("pw"), FAST).unwrap();
|
||||||
|
v.provision_record(entry(0, Outcome::Refused)).unwrap();
|
||||||
|
let before = v.provision_audit().to_vec();
|
||||||
|
v.provision_record(entry(1, Outcome::Accepted)).unwrap();
|
||||||
|
// Recording appends; what was there is unchanged.
|
||||||
|
assert_eq!(&v.provision_audit()[..1], before.as_slice());
|
||||||
|
assert_eq!(v.provision_audit()[1], entry(1, Outcome::Accepted));
|
||||||
|
|
||||||
|
assert_eq!(AUDIT_LIMIT, 5_000);
|
||||||
|
for i in 2..(AUDIT_LIMIT as i64 + 3) {
|
||||||
|
v.provision_record(entry(i, Outcome::Expired)).unwrap();
|
||||||
|
}
|
||||||
|
let audit = v.provision_audit();
|
||||||
|
assert_eq!(audit.len(), AUDIT_LIMIT);
|
||||||
|
// The three oldest went; the newest is last.
|
||||||
|
assert_eq!(audit[0].at, NOW + 3);
|
||||||
|
assert_eq!(audit.last().unwrap().at, NOW + AUDIT_LIMIT as i64 + 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_entry_has_no_member_that_could_hold_a_secret() {
|
||||||
|
// Every member, with every option set: the JSON has exactly these names and nothing like a value.
|
||||||
|
let mut e = entry(0, Outcome::Accepted);
|
||||||
|
e.replaced = true;
|
||||||
|
let json: serde_json::Value = serde_json::to_value(&e).unwrap();
|
||||||
|
let mut names: Vec<&str> = json.as_object().unwrap().keys().map(String::as_str).collect();
|
||||||
|
names.sort();
|
||||||
|
assert_eq!(names, ["at", "code", "direction", "host", "item", "kind", "outcome", "replaced", "run", "store"]);
|
||||||
|
for v in json.as_object().unwrap().values() {
|
||||||
|
assert!(!v.is_object() && !v.is_array(), "no nested member to hide a value in");
|
||||||
|
}
|
||||||
|
assert_eq!(
|
||||||
|
serde_json::to_string(&e).unwrap(),
|
||||||
|
r#"{"at":1793750000000,"direction":"offer","host":"nixos-vm","item":"fabrica/gitea-read-token","store":"vault","run":"deploy-7","kind":"Gitea token, read:repository","code":"684361","outcome":"accepted","replaced":true}"#
|
||||||
|
);
|
||||||
|
// The options are left out when absent; the outcomes are spelled as docs/FORMAT.md says.
|
||||||
|
let mut e = entry(0, Outcome::OutOfScope);
|
||||||
|
e.run = None;
|
||||||
|
e.kind = None;
|
||||||
|
let s = serde_json::to_string(&e).unwrap();
|
||||||
|
assert!(!s.contains("\"run\"") && !s.contains("\"kind\"") && s.contains("\"out-of-scope\""), "{s}");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- display offers (core 0.12.0) ----
|
||||||
|
|
||||||
|
fn display(i: i64, outcome: Outcome) -> ProvisionEntry {
|
||||||
|
ProvisionEntry {
|
||||||
|
item: "arca/authelia-mark".into(),
|
||||||
|
store: Store::Display,
|
||||||
|
kind: Some("totp".into()),
|
||||||
|
run: None,
|
||||||
|
..entry(i, outcome)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_display_offer_is_recorded_as_confirmed_and_survives_a_reopen() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let path = dir.path().join("v.custos");
|
||||||
|
let mut v = Vault::create(&SecretString::from("pw"), FAST).unwrap();
|
||||||
|
for (i, o) in [Outcome::Confirmed, Outcome::Refused, Outcome::Expired, Outcome::Invalid, Outcome::OutOfScope]
|
||||||
|
.into_iter()
|
||||||
|
.enumerate()
|
||||||
|
{
|
||||||
|
v.provision_record(display(i as i64, o)).unwrap();
|
||||||
|
}
|
||||||
|
let s = serde_json::to_string(&v.provision_audit()[0]).unwrap();
|
||||||
|
assert!(s.contains(r#""store":"display""#) && s.contains(r#""outcome":"confirmed""#), "{s}");
|
||||||
|
v.save(&path).unwrap();
|
||||||
|
let back = Vault::open_file(&path, &SecretString::from("pw")).unwrap();
|
||||||
|
assert_eq!(back.provision_audit(), v.provision_audit());
|
||||||
|
assert_eq!(back.provision_audit()[0].outcome, Outcome::Confirmed);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn display_and_confirmed_go_only_together_and_store_nothing() {
|
||||||
|
let mut v = Vault::create(&SecretString::from("pw"), FAST).unwrap();
|
||||||
|
let bad: Vec<ProvisionEntry> = vec![
|
||||||
|
// Nothing is stored, so nothing is accepted, approved, generated or replaced.
|
||||||
|
display(0, Outcome::Accepted),
|
||||||
|
display(0, Outcome::Approved),
|
||||||
|
display(0, Outcome::Generated),
|
||||||
|
ProvisionEntry { replaced: true, ..display(0, Outcome::Confirmed) },
|
||||||
|
// A display is an offer.
|
||||||
|
ProvisionEntry { direction: Direction::Ask, ..display(0, Outcome::Confirmed) },
|
||||||
|
// Confirmed is a display offer's outcome only.
|
||||||
|
entry(0, Outcome::Confirmed),
|
||||||
|
ProvisionEntry { store: Store::Claude, ..entry(0, Outcome::Confirmed) },
|
||||||
|
];
|
||||||
|
for (i, e) in bad.into_iter().enumerate() {
|
||||||
|
assert!(matches!(v.provision_record(e), Err(Error::Provision(_))), "case {i}");
|
||||||
|
}
|
||||||
|
assert!(v.provision_audit().is_empty());
|
||||||
|
}
|
||||||
@@ -0,0 +1,269 @@
|
|||||||
|
//! The security member (docs/FORMAT.md, "The security member"): the level rules, the checklist and its audit, the
|
||||||
|
//! kept scope, and the rules the app asks before a card. That an older reader still opens such a vault, and that
|
||||||
|
//! unknown values are refused, are unit tests in src/security.rs, which can see the decrypted body.
|
||||||
|
|
||||||
|
use std::collections::BTreeSet;
|
||||||
|
|
||||||
|
use custos_vault::security::{
|
||||||
|
AUDIT_LIMIT, Action, Auth, Item, KeptScope, Level, SETUP_WINDOW, SshRule, Window, accept_all_allowed,
|
||||||
|
hello_for_approvals, replacing_line_preticked, ssh_needs_auth, totp_offer_allowed,
|
||||||
|
};
|
||||||
|
use custos_vault::{Error, KdfParams, SecretString, Vault};
|
||||||
|
|
||||||
|
const FAST: KdfParams = KdfParams { m_cost_kib: 64, t_cost: 1, p_cost: 1 };
|
||||||
|
const NOW: i64 = 1_793_750_000_000;
|
||||||
|
const HOUR: i64 = 3_600_000;
|
||||||
|
|
||||||
|
fn vault() -> Vault {
|
||||||
|
Vault::create(&SecretString::from("pw"), FAST).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn actions(v: &Vault) -> Vec<Action> {
|
||||||
|
v.security_view(NOW).audit.iter().map(|e| e.action).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn s(v: &[&str]) -> Vec<String> {
|
||||||
|
v.iter().map(|x| x.to_string()).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_vault_that_never_had_setup_is_standard() {
|
||||||
|
let v = vault();
|
||||||
|
assert_eq!(v.security_level(NOW), Level::Standard);
|
||||||
|
let view = v.security_view(NOW);
|
||||||
|
assert_eq!(view.level, Level::Standard);
|
||||||
|
assert!(view.setup.is_none() && view.setup_remaining.is_none());
|
||||||
|
assert!(view.ticked.is_empty() && view.audit.is_empty() && view.kept_scope.is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn setup_lasts_two_hours_from_its_start() {
|
||||||
|
assert_eq!(SETUP_WINDOW, 2 * HOUR);
|
||||||
|
let mut v = vault();
|
||||||
|
let w = v.security_start_setup(NOW);
|
||||||
|
assert_eq!(w, Window { started: NOW, until: NOW + 2 * HOUR });
|
||||||
|
assert_eq!(v.security_level(NOW), Level::Setup);
|
||||||
|
assert_eq!(v.security_level(NOW + 2 * HOUR - 1), Level::Setup, "the last millisecond is still Setup");
|
||||||
|
assert_eq!(v.security_level(NOW + 2 * HOUR), Level::Standard, "`until` itself is not");
|
||||||
|
assert_eq!(v.security_level(NOW - 1), Level::Standard, "a clock set back before the start is not Setup");
|
||||||
|
assert_eq!(v.security_view(NOW + HOUR).setup_remaining, Some(HOUR));
|
||||||
|
assert_eq!(v.security_view(NOW + 2 * HOUR).setup_remaining, None);
|
||||||
|
assert_eq!(actions(&v), [Action::SetupStarted]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn starting_setup_again_while_in_setup_extends_nothing() {
|
||||||
|
let mut v = vault();
|
||||||
|
let w = v.security_start_setup(NOW);
|
||||||
|
assert_eq!(v.security_start_setup(NOW + HOUR), w);
|
||||||
|
assert_eq!(v.security_level(NOW + 2 * HOUR), Level::Standard);
|
||||||
|
assert_eq!(actions(&v), [Action::SetupStarted], "no second entry");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn finish_setup_ends_it_early_and_is_audited() {
|
||||||
|
let mut v = vault();
|
||||||
|
assert!(!v.security_finish_setup(NOW), "nothing to finish");
|
||||||
|
v.security_start_setup(NOW);
|
||||||
|
assert!(v.security_finish_setup(NOW + 10));
|
||||||
|
assert_eq!(v.security_level(NOW + 10), Level::Standard);
|
||||||
|
assert_eq!(v.security_view(NOW + 10).finished, Some(NOW + 10));
|
||||||
|
assert!(!v.security_finish_setup(NOW + 20), "once");
|
||||||
|
assert_eq!(actions(&v), [Action::SetupStarted, Action::SetupFinished]);
|
||||||
|
// A later Connect via SSH starts a new window.
|
||||||
|
let w = v.security_start_setup(NOW + HOUR);
|
||||||
|
assert_eq!(w, Window { started: NOW + HOUR, until: NOW + 3 * HOUR });
|
||||||
|
assert_eq!(v.security_level(NOW + HOUR), Level::Setup);
|
||||||
|
assert_eq!(v.security_view(NOW + HOUR).finished, None);
|
||||||
|
assert_eq!(actions(&v), [Action::SetupStarted, Action::SetupFinished, Action::SetupStarted]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn expiry_is_audited_once_by_the_first_change_that_notices_it() {
|
||||||
|
let mut v = vault();
|
||||||
|
v.security_start_setup(NOW);
|
||||||
|
// Reading notices nothing.
|
||||||
|
assert_eq!(v.security_level(NOW + 3 * HOUR), Level::Standard);
|
||||||
|
assert_eq!(actions(&v), [Action::SetupStarted]);
|
||||||
|
v.security_tick(Item::NoSsh, NOW + 3 * HOUR);
|
||||||
|
v.security_record(Action::SshConnected, None, NOW + 3 * HOUR + 1).unwrap();
|
||||||
|
assert!(!v.security_finish_setup(NOW + 3 * HOUR + 2));
|
||||||
|
assert_eq!(actions(&v), [Action::SetupStarted, Action::SetupExpired, Action::Ticked, Action::SshConnected]);
|
||||||
|
let view = v.security_view(NOW + 3 * HOUR);
|
||||||
|
assert_eq!(view.finished, Some(NOW + 2 * HOUR), "ended at `until`");
|
||||||
|
assert_eq!(view.audit[1].at, NOW + 3 * HOUR, "written when noticed");
|
||||||
|
// Starting again after expiry opens a new window.
|
||||||
|
let w = v.security_start_setup(NOW + 4 * HOUR);
|
||||||
|
assert_eq!(w.started, NOW + 4 * HOUR);
|
||||||
|
assert_eq!(*actions(&v).last().unwrap(), Action::SetupStarted);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn ticking_hardens_and_undoing_needs_hello_or_the_password_and_is_audited() {
|
||||||
|
let mut v = vault();
|
||||||
|
assert!(v.security_tick(Item::HelloApprovals, NOW));
|
||||||
|
assert!(!v.security_tick(Item::HelloApprovals, NOW + 1), "ticked already: no entry");
|
||||||
|
assert_eq!(v.security_level(NOW), Level::Hardened);
|
||||||
|
assert!(v.security_tick(Item::NoSsh, NOW + 2));
|
||||||
|
assert!(v.security_untick(Item::NoSsh, Auth::Hello, NOW + 3));
|
||||||
|
assert!(!v.security_untick(Item::NoSsh, Auth::Password, NOW + 4), "not ticked: no entry");
|
||||||
|
assert_eq!(v.security_level(NOW + 5), Level::Hardened);
|
||||||
|
assert!(v.security_untick(Item::HelloApprovals, Auth::Password, NOW + 5));
|
||||||
|
assert_eq!(v.security_level(NOW + 6), Level::Standard);
|
||||||
|
|
||||||
|
let audit = v.security_view(NOW + 6).audit;
|
||||||
|
let got: Vec<_> = audit.iter().map(|e| (e.at, e.action, e.item, e.auth)).collect();
|
||||||
|
assert_eq!(
|
||||||
|
got,
|
||||||
|
[
|
||||||
|
(NOW, Action::Ticked, Some(Item::HelloApprovals), None),
|
||||||
|
(NOW + 2, Action::Ticked, Some(Item::NoSsh), None),
|
||||||
|
(NOW + 3, Action::Unticked, Some(Item::NoSsh), Some(Auth::Hello)),
|
||||||
|
(NOW + 5, Action::Unticked, Some(Item::HelloApprovals), Some(Auth::Password)),
|
||||||
|
]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn ticked_items_hold_during_setup() {
|
||||||
|
let mut v = vault();
|
||||||
|
v.security_tick(Item::NoSsh, NOW);
|
||||||
|
v.security_tick(Item::TotpOnPhone, NOW);
|
||||||
|
v.security_start_setup(NOW + 1);
|
||||||
|
assert_eq!(v.security_level(NOW + 1), Level::Setup);
|
||||||
|
let ticked = v.security_view(NOW + 1).ticked;
|
||||||
|
assert_eq!(ticked, BTreeSet::from([Item::TotpOnPhone, Item::NoSsh]));
|
||||||
|
assert_eq!(ssh_needs_auth(Level::Setup, &ticked), SshRule::Off, "Setup never undoes hardening");
|
||||||
|
assert!(!totp_offer_allowed(&ticked));
|
||||||
|
// After Setup the ticks are still there: Hardened.
|
||||||
|
assert_eq!(v.security_level(NOW + 3 * HOUR), Level::Hardened);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_state_survives_a_reopen() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let path = dir.path().join("v.custos");
|
||||||
|
let mut v = vault();
|
||||||
|
v.security_start_setup(NOW);
|
||||||
|
v.security_tick(Item::NarrowScope, NOW + 1);
|
||||||
|
v.security_keep_scope(&s(&["arca/"]), &s(&["arca/", "fabrica/"])).unwrap();
|
||||||
|
v.security_record(Action::TotpMoved, Some(Item::TotpOnPhone), NOW + 2).unwrap();
|
||||||
|
v.save(&path).unwrap();
|
||||||
|
let back = Vault::open_file(&path, &SecretString::from("pw")).unwrap();
|
||||||
|
assert_eq!(back.security_view(NOW + 3), v.security_view(NOW + 3));
|
||||||
|
assert_eq!(back.security_level(NOW + 3), Level::Setup);
|
||||||
|
let view = back.security_view(NOW + 3);
|
||||||
|
assert_eq!(view.kept_scope, Some(KeptScope { ask: s(&["arca/"]), offer: s(&["arca/", "fabrica/"]) }));
|
||||||
|
assert_eq!(view.audit.last().unwrap().item, Some(Item::TotpOnPhone));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_kept_scope_is_kept_once_and_taken_back() {
|
||||||
|
let mut v = vault();
|
||||||
|
assert!(v.security_take_kept_scope().is_none());
|
||||||
|
v.security_keep_scope(&s(&["arca/"]), &s(&["fabrica/"])).unwrap();
|
||||||
|
// A second keep would lose the first prefixes: refused.
|
||||||
|
assert!(matches!(v.security_keep_scope(&s(&["x/"]), &[]), Err(Error::Security(_))));
|
||||||
|
let kept = v.security_take_kept_scope().unwrap();
|
||||||
|
assert_eq!(kept, KeptScope { ask: s(&["arca/"]), offer: s(&["fabrica/"]) });
|
||||||
|
assert!(v.security_take_kept_scope().is_none());
|
||||||
|
// The rules for a prefix.
|
||||||
|
for bad in [s(&[""]), s(&["a\nb"]), vec!["x".repeat(201)], (0..65).map(|i| format!("p{i}/")).collect()] {
|
||||||
|
assert!(matches!(v.security_keep_scope(&bad, &[]), Err(Error::Security(_))), "{bad:?}");
|
||||||
|
assert!(matches!(v.security_keep_scope(&[], &bad), Err(Error::Security(_))), "{bad:?}");
|
||||||
|
}
|
||||||
|
v.security_keep_scope(&[], &[]).unwrap();
|
||||||
|
assert_eq!(v.security_take_kept_scope(), Some(KeptScope { ask: vec![], offer: vec![] }));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn only_ssh_connected_and_totp_moved_are_recorded_directly() {
|
||||||
|
let mut v = vault();
|
||||||
|
v.security_record(Action::SshConnected, None, NOW).unwrap();
|
||||||
|
v.security_record(Action::TotpMoved, None, NOW + 1).unwrap();
|
||||||
|
for a in [Action::SetupStarted, Action::SetupFinished, Action::SetupExpired, Action::Ticked, Action::Unticked] {
|
||||||
|
assert!(matches!(v.security_record(a, Some(Item::NoSsh), NOW + 2), Err(Error::Security(_))), "{a:?}");
|
||||||
|
}
|
||||||
|
assert_eq!(actions(&v), [Action::SshConnected, Action::TotpMoved]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_audit_keeps_the_newest_5000() {
|
||||||
|
assert_eq!(AUDIT_LIMIT, 5_000);
|
||||||
|
let mut v = vault();
|
||||||
|
for i in 0..(AUDIT_LIMIT as i64 + 2) {
|
||||||
|
v.security_record(Action::SshConnected, None, NOW + i).unwrap();
|
||||||
|
}
|
||||||
|
let audit = v.security_view(NOW).audit;
|
||||||
|
assert_eq!(audit.len(), AUDIT_LIMIT);
|
||||||
|
assert_eq!(audit[0].at, NOW + 2);
|
||||||
|
assert_eq!(audit.last().unwrap().at, NOW + AUDIT_LIMIT as i64 + 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_rules_before_a_card() {
|
||||||
|
let none = BTreeSet::new();
|
||||||
|
// Accept all: only in Setup, only for a setup run with Provisio lines only.
|
||||||
|
assert!(accept_all_allowed(Level::Setup, "setup-1", true));
|
||||||
|
assert!(!accept_all_allowed(Level::Setup, "setup-1", false), "a signing or approval line");
|
||||||
|
assert!(!accept_all_allowed(Level::Setup, "r-42", true), "not a setup run");
|
||||||
|
assert!(!accept_all_allowed(Level::Setup, "Setup-1", true), "the prefix is exact");
|
||||||
|
assert!(!accept_all_allowed(Level::Standard, "setup-1", true));
|
||||||
|
assert!(!accept_all_allowed(Level::Hardened, "setup-1", true));
|
||||||
|
// A line that replaces a stored item is pre-ticked only where Accept all applies.
|
||||||
|
assert!(replacing_line_preticked(Level::Setup, true));
|
||||||
|
assert!(!replacing_line_preticked(Level::Setup, false));
|
||||||
|
assert!(!replacing_line_preticked(Level::Standard, true));
|
||||||
|
assert!(!replacing_line_preticked(Level::Hardened, true));
|
||||||
|
// Connect via SSH.
|
||||||
|
assert_eq!(ssh_needs_auth(Level::Setup, &none), SshRule::Allowed);
|
||||||
|
assert_eq!(ssh_needs_auth(Level::Standard, &none), SshRule::NeedsAuth);
|
||||||
|
let hello = BTreeSet::from([Item::HelloApprovals]);
|
||||||
|
assert_eq!(ssh_needs_auth(Level::Hardened, &hello), SshRule::NeedsAuth);
|
||||||
|
let off = BTreeSet::from([Item::NoSsh]);
|
||||||
|
for l in [Level::Setup, Level::Standard, Level::Hardened] {
|
||||||
|
assert_eq!(ssh_needs_auth(l, &off), SshRule::Off);
|
||||||
|
}
|
||||||
|
// TOTP offers and Hello for approvals.
|
||||||
|
assert!(totp_offer_allowed(&none) && totp_offer_allowed(&hello));
|
||||||
|
assert!(!totp_offer_allowed(&BTreeSet::from([Item::TotpOnPhone])));
|
||||||
|
assert!(hello_for_approvals(&hello) && !hello_for_approvals(&none) && !hello_for_approvals(&off));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn values_are_spelled_as_docs_format_says() {
|
||||||
|
let all = [
|
||||||
|
Item::TotpOnPhone,
|
||||||
|
Item::HelloApprovals,
|
||||||
|
Item::NarrowScope,
|
||||||
|
Item::RotateSetup,
|
||||||
|
Item::NoSsh,
|
||||||
|
Item::PhoneApproves,
|
||||||
|
];
|
||||||
|
assert_eq!(
|
||||||
|
serde_json::to_string(&all).unwrap(),
|
||||||
|
r#"["totp-on-phone","hello-approvals","narrow-scope","rotate-setup","no-ssh","phone-approves"]"#
|
||||||
|
);
|
||||||
|
let actions = [
|
||||||
|
Action::SetupStarted,
|
||||||
|
Action::SetupFinished,
|
||||||
|
Action::SetupExpired,
|
||||||
|
Action::Ticked,
|
||||||
|
Action::Unticked,
|
||||||
|
Action::SshConnected,
|
||||||
|
Action::TotpMoved,
|
||||||
|
];
|
||||||
|
assert_eq!(
|
||||||
|
serde_json::to_string(&actions).unwrap(),
|
||||||
|
r#"["setup-started","setup-finished","setup-expired","ticked","unticked","ssh-connected","totp-moved"]"#
|
||||||
|
);
|
||||||
|
assert_eq!(serde_json::to_string(&[Auth::Hello, Auth::Password]).unwrap(), r#"["hello","password"]"#);
|
||||||
|
assert_eq!(
|
||||||
|
serde_json::to_string(&[Level::Setup, Level::Standard, Level::Hardened]).unwrap(),
|
||||||
|
r#"["setup","standard","hardened"]"#
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
serde_json::to_string(&[SshRule::Allowed, SshRule::NeedsAuth, SshRule::Off]).unwrap(),
|
||||||
|
r#"["allowed","needs-auth","off"]"#
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -29,6 +29,7 @@ fn ctx(pipeline: &str, repo: &str, trigger: &str) -> Context {
|
|||||||
file: "Arca_0.2.0_x64-setup.exe".into(),
|
file: "Arca_0.2.0_x64-setup.exe".into(),
|
||||||
size: 25_145_977,
|
size: 25_145_977,
|
||||||
sha256: "c4995c6e2e0c20fec7e8dcb05d70144da58f42d379c6705df66edb42abafb8a3".into(),
|
sha256: "c4995c6e2e0c20fec7e8dcb05d70144da58f42d379c6705df66edb42abafb8a3".into(),
|
||||||
|
..Default::default()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -38,6 +39,8 @@ fn minisign_req(key: &str, c: Context) -> Request {
|
|||||||
kind: SignKind::Minisign,
|
kind: SignKind::Minisign,
|
||||||
digest: vec![7; 64],
|
digest: vec![7; 64],
|
||||||
manifest: None,
|
manifest: None,
|
||||||
|
approval: None,
|
||||||
|
run: None,
|
||||||
context: c,
|
context: c,
|
||||||
via: Via::Local,
|
via: Via::Local,
|
||||||
}
|
}
|
||||||
@@ -49,6 +52,8 @@ fn authenticode_req(key: &str, c: Context) -> Request {
|
|||||||
kind: SignKind::Authenticode,
|
kind: SignKind::Authenticode,
|
||||||
digest: vec![9; 32],
|
digest: vec![9; 32],
|
||||||
manifest: None,
|
manifest: None,
|
||||||
|
approval: None,
|
||||||
|
run: None,
|
||||||
context: c,
|
context: c,
|
||||||
via: Via::Remote,
|
via: Via::Remote,
|
||||||
}
|
}
|
||||||
@@ -61,13 +66,21 @@ fn the_release_and_test_sets_are_made_once_each() {
|
|||||||
let ids: Vec<&str> = keys.iter().map(|k| k.id.as_str()).collect();
|
let ids: Vec<&str> = keys.iter().map(|k| k.id.as_str()).collect();
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
ids,
|
ids,
|
||||||
["domi-release", "domi-root", "domi-code-signing", "domi-test", "domi-test-root", "domi-test-code-signing"]
|
[
|
||||||
|
"domi-release",
|
||||||
|
"domi-root",
|
||||||
|
"domi-code-signing",
|
||||||
|
"domi-approve",
|
||||||
|
"domi-test",
|
||||||
|
"domi-test-root",
|
||||||
|
"domi-test-code-signing"
|
||||||
|
]
|
||||||
);
|
);
|
||||||
assert_eq!(keys[1].kind, KeyKind::RootCa);
|
assert_eq!(keys[1].kind, KeyKind::RootCa);
|
||||||
assert_eq!(keys[2].issuer.as_deref(), Some("domi-root"));
|
assert_eq!(keys[2].issuer.as_deref(), Some("domi-root"));
|
||||||
assert_eq!(keys[5].issuer.as_deref(), Some("domi-test-root"));
|
assert_eq!(keys[6].issuer.as_deref(), Some("domi-test-root"));
|
||||||
assert!(!keys[0].auto_approve && !keys[2].auto_approve);
|
assert!(!keys[0].auto_approve && !keys[2].auto_approve && !keys[3].auto_approve);
|
||||||
assert!(keys[3].auto_approve && keys[5].auto_approve && !keys[4].auto_approve);
|
assert!(keys[4].auto_approve && keys[6].auto_approve && !keys[5].auto_approve);
|
||||||
assert!(keys[0].minisign_public.as_deref().unwrap().starts_with("untrusted comment: minisign public key "));
|
assert!(keys[0].minisign_public.as_deref().unwrap().starts_with("untrusted comment: minisign public key "));
|
||||||
assert!(matches!(v.signing_create(Role::Release, &[], &[], NOW), Err(Error::SigningExists("release"))));
|
assert!(matches!(v.signing_create(Role::Release, &[], &[], NOW), Err(Error::SigningExists("release"))));
|
||||||
// The root's certificate is exported; a key without one is not.
|
// The root's certificate is exported; a key without one is not.
|
||||||
@@ -205,3 +218,177 @@ fn the_audit_log_records_every_outcome_and_survives_a_reopen() {
|
|||||||
let mut reopened = reopened;
|
let mut reopened = reopened;
|
||||||
assert!(reopened.signing_sign(&rel, Approval::Mark, NOW + 7).is_ok());
|
assert!(reopened.signing_sign(&rel, Approval::Mark, NOW + 7).is_ok());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ---- deploy approvals (core 0.12.0) ----
|
||||||
|
|
||||||
|
const COMMIT: &str = "6925d0cb08b9e0c5c3a4a7a2c37b7f2a9f7ed3b1";
|
||||||
|
|
||||||
|
fn approval_text(run: &str, repo: &str, expires_in: i64) -> String {
|
||||||
|
format!(
|
||||||
|
r#"{{"v":1,"run":"{run}","repo":"{repo}","commit":"{COMMIT}","pipeline":"release","version":"0.7.0","targets":["deploy to nixos-vm","publish to Aula"],"expires":{}}}"#,
|
||||||
|
NOW / 1000 + expires_in
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn approval_req(run: &str) -> Request {
|
||||||
|
Request {
|
||||||
|
key: "domi-approve".into(),
|
||||||
|
kind: SignKind::Approval,
|
||||||
|
digest: vec![],
|
||||||
|
manifest: None,
|
||||||
|
approval: Some(approval_text(run, "Arca", 600)),
|
||||||
|
run: Some(run.into()),
|
||||||
|
context: Context {
|
||||||
|
repo: "Arca".into(),
|
||||||
|
pipeline: "release".into(),
|
||||||
|
trigger: "tag".into(),
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
via: Via::Remote,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn domi_approve_is_made_with_the_release_keys() {
|
||||||
|
let v = vault_with_keys();
|
||||||
|
let keys = v.signing_keys();
|
||||||
|
let a = keys.iter().find(|k| k.id == "domi-approve").expect("made with the release set");
|
||||||
|
assert_eq!(a.kind, KeyKind::Ed25519);
|
||||||
|
assert_eq!(a.role, Role::Release);
|
||||||
|
assert_eq!(a.name, "Domi deploy approval");
|
||||||
|
assert!(!a.auto_approve, "it always asks");
|
||||||
|
let rel = keys.iter().find(|k| k.id == "domi-release").unwrap();
|
||||||
|
assert_eq!((&a.pipelines, &a.repos), (&rel.pipelines, &rel.repos), "the release keys' scope");
|
||||||
|
assert!(a.minisign_public.as_deref().unwrap().starts_with("untrusted comment: minisign public key "));
|
||||||
|
assert_ne!(a.key_id, rel.key_id);
|
||||||
|
// The test set has no approval key.
|
||||||
|
assert!(!keys.iter().any(|k| k.role == Role::Test && k.id.contains("approve")));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_approval_is_signed_by_domi_approve_and_verifies_with_minisign() {
|
||||||
|
let mut v = vault_with_keys();
|
||||||
|
let req = approval_req("r-42");
|
||||||
|
v.signing_check_at(&req, NOW).unwrap();
|
||||||
|
let signed = v.signing_sign(&req, Approval::Mark, NOW).unwrap();
|
||||||
|
let text = String::from_utf8(signed.bytes.clone()).unwrap();
|
||||||
|
let pubkey = v.signing_keys().into_iter().find(|k| k.id == "domi-approve").unwrap().minisign_public.unwrap();
|
||||||
|
let public = minisign_verify::PublicKey::decode(&pubkey).unwrap();
|
||||||
|
let sig = minisign_verify::Signature::decode(&text).unwrap();
|
||||||
|
public.verify(req.approval.as_deref().unwrap().as_bytes(), &sig, false).unwrap();
|
||||||
|
assert_eq!(sig.trusted_comment(), format!("timestamp:{}\tfile:approval-r-42.json\thashed", NOW / 1000));
|
||||||
|
assert_eq!(signed.sha256, custos_sign::sha256_hex(&signed.bytes));
|
||||||
|
|
||||||
|
let e = v.signing_audit().last().unwrap();
|
||||||
|
assert_eq!((e.key.as_str(), e.kind, e.outcome), ("domi-approve", SignKind::Approval, Outcome::Approved));
|
||||||
|
assert_eq!(e.run.as_deref(), Some("r-42"));
|
||||||
|
assert_eq!(e.context.file, "approval-r-42.json");
|
||||||
|
assert_eq!((e.context.commit.as_str(), e.context.version.as_str()), (COMMIT, "0.7.0"), "filled from the JSON");
|
||||||
|
assert_eq!(e.signature.as_deref(), Some(signed.sha256.as_str()));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn domi_approve_signs_only_approvals_and_approvals_only_with_domi_approve() {
|
||||||
|
let mut v = vault_with_keys();
|
||||||
|
let by_release = Request { key: "domi-release".into(), ..approval_req("r-42") };
|
||||||
|
let by_test = Request { key: "domi-test".into(), ..approval_req("r-42") };
|
||||||
|
let mut digest = minisign_req("domi-approve", ctx("release", "Arca", "tag"));
|
||||||
|
digest.run = Some("r-42".into());
|
||||||
|
let sums = format!("{} Arca_0.2.0_x64-setup.exe\n", "c".repeat(64));
|
||||||
|
let manifest = Request { kind: SignKind::Manifest, digest: vec![], manifest: Some(sums), ..digest.clone() };
|
||||||
|
let authenticode = Request { kind: SignKind::Authenticode, digest: vec![1; 32], ..digest.clone() };
|
||||||
|
for r in [&by_release, &by_test, &digest, &manifest, &authenticode] {
|
||||||
|
assert!(matches!(v.signing_check_at(r, NOW), Err(Refusal::Invalid(_))), "{r:?}");
|
||||||
|
assert!(matches!(v.signing_sign(r, Approval::Mark, NOW), Err(Refusal::Invalid(_))), "{r:?}");
|
||||||
|
}
|
||||||
|
let code_signing = Request { key: "domi-code-signing".into(), ..approval_req("r-42") };
|
||||||
|
assert!(matches!(v.signing_check_at(&code_signing, NOW), Err(Refusal::Invalid(_))));
|
||||||
|
// A release key: never without Mark.
|
||||||
|
assert!(matches!(v.signing_sign(&approval_req("r-42"), Approval::Auto, NOW), Err(Refusal::NeedsApproval(_))));
|
||||||
|
assert!(v.signing_audit().iter().all(|e| e.signature.is_none()), "nothing was signed");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_approval_needs_its_run_a_canonical_unexpired_text_and_a_matching_context() {
|
||||||
|
let mut v = vault_with_keys();
|
||||||
|
let invalid = |v: &mut Vault, r: &Request| {
|
||||||
|
assert!(matches!(v.signing_check_at(r, NOW), Err(Refusal::Invalid(_))), "{r:?}");
|
||||||
|
assert!(matches!(v.signing_sign(r, Approval::Mark, NOW), Err(Refusal::Invalid(_))), "{r:?}");
|
||||||
|
};
|
||||||
|
invalid(&mut v, &Request { run: None, ..approval_req("r-42") });
|
||||||
|
invalid(&mut v, &Request { run: Some("r-43".into()), ..approval_req("r-42") });
|
||||||
|
invalid(&mut v, &Request { approval: None, ..approval_req("r-42") });
|
||||||
|
let mut spaced = approval_req("r-42");
|
||||||
|
spaced.approval = Some(spaced.approval.unwrap().replace(',', ", "));
|
||||||
|
invalid(&mut v, &spaced);
|
||||||
|
let mut late = approval_req("r-42");
|
||||||
|
late.approval = Some(approval_text("r-42", "Arca", 3601));
|
||||||
|
invalid(&mut v, &late);
|
||||||
|
let mut past = approval_req("r-42");
|
||||||
|
past.approval = Some(approval_text("r-42", "Arca", 0));
|
||||||
|
invalid(&mut v, &past);
|
||||||
|
let zeros = "0".repeat(40);
|
||||||
|
for (member, value) in
|
||||||
|
[("repo", "Fabrica"), ("pipeline", "nightly"), ("commit", zeros.as_str()), ("version", "0.8.0")]
|
||||||
|
{
|
||||||
|
let mut r = approval_req("r-42");
|
||||||
|
match member {
|
||||||
|
"repo" => r.context.repo = value.into(),
|
||||||
|
"pipeline" => r.context.pipeline = value.into(),
|
||||||
|
"commit" => r.context.commit = value.into(),
|
||||||
|
_ => r.context.version = value.into(),
|
||||||
|
}
|
||||||
|
invalid(&mut v, &r);
|
||||||
|
}
|
||||||
|
// The expiry is checked against the time given: valid now, expired ten minutes later.
|
||||||
|
let ok = approval_req("r-42");
|
||||||
|
assert!(v.signing_check_at(&ok, NOW).is_ok());
|
||||||
|
assert!(matches!(v.signing_check_at(&ok, NOW + 600_000), Err(Refusal::Invalid(_))));
|
||||||
|
assert!(matches!(v.signing_sign(&ok, Approval::Mark, NOW + 600_000), Err(Refusal::Invalid(_))));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_approval_for_a_repo_off_the_list_is_out_of_scope() {
|
||||||
|
let mut v = vault_with_keys();
|
||||||
|
let mut r = approval_req("r-42");
|
||||||
|
r.approval = Some(approval_text("r-42", "Custos", 600));
|
||||||
|
r.context.repo = "Custos".into();
|
||||||
|
assert!(matches!(v.signing_check_at(&r, NOW), Err(Refusal::OutOfScope(_))));
|
||||||
|
// The JSON's repo is what counts, even when the context leaves it empty.
|
||||||
|
r.context.repo = String::new();
|
||||||
|
assert!(matches!(v.signing_sign(&r, Approval::Mark, NOW), Err(Refusal::OutOfScope(_))));
|
||||||
|
assert_eq!(v.signing_audit().last().unwrap().outcome, Outcome::OutOfScope);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn any_request_may_name_its_run_and_the_audit_keeps_it() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let path = dir.path().join("v.custos");
|
||||||
|
let mut v = vault_with_keys();
|
||||||
|
let mut r = minisign_req("domi-release", ctx("release", "Arca", "tag"));
|
||||||
|
r.run = Some("r-42".into());
|
||||||
|
r.context.version = "0.7.0".into();
|
||||||
|
v.signing_sign(&r, Approval::Mark, NOW).unwrap();
|
||||||
|
v.signing_refuse(&r, Outcome::Refused, None, NOW + 1);
|
||||||
|
let mut bad = r.clone();
|
||||||
|
bad.run = Some("r 42".into());
|
||||||
|
assert!(matches!(v.signing_check_at(&bad, NOW), Err(Refusal::Invalid(_))));
|
||||||
|
let mut stray = r.clone();
|
||||||
|
stray.approval = Some(approval_text("r-42", "Arca", 600));
|
||||||
|
assert!(matches!(v.signing_check_at(&stray, NOW), Err(Refusal::Invalid(_))), "approval text on a digest request");
|
||||||
|
v.save(&path).unwrap();
|
||||||
|
let back = Vault::open_file(&path, &SecretString::from("pw")).unwrap();
|
||||||
|
let a = back.signing_audit();
|
||||||
|
assert_eq!(a[0].run.as_deref(), Some("r-42"));
|
||||||
|
assert_eq!(a[0].context.version, "0.7.0");
|
||||||
|
assert_eq!(a[1].run.as_deref(), Some("r-42"));
|
||||||
|
assert_eq!(back.signing_audit(), v.signing_audit());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_approval_key_is_added_only_to_release_keys_and_only_once() {
|
||||||
|
let mut empty = Vault::create(&SecretString::from("pw"), FAST).unwrap();
|
||||||
|
assert!(matches!(empty.signing_add_approve(NOW), Err(Error::Signing(_))), "no release keys");
|
||||||
|
let mut v = vault_with_keys();
|
||||||
|
assert!(matches!(v.signing_add_approve(NOW), Err(Error::SigningExists("approval"))));
|
||||||
|
}
|
||||||
|
|||||||
+94
-1
@@ -119,7 +119,8 @@ UTF-8 JSON, held in zeroizing buffers while being encrypted or parsed:
|
|||||||
- `fields` is an ordered list; a name may repeat (several `url`s). Unknown names are kept as custom fields.
|
- `fields` is an ordered list; a name may repeat (several `url`s). Unknown names are kept as custom fields.
|
||||||
- `history` keeps the previous value of a secret field each time it changes (newest last, at most 20 per item).
|
- `history` keeps the previous value of a secret field each time it changes (newest last, at most 20 per item).
|
||||||
- Readers ignore JSON members they do not know, so later versions can add them.
|
- Readers ignore JSON members they do not know, so later versions can add them.
|
||||||
- `identity` (optional, core 0.7.0): the Domi identity's root key and the certs it issued (docs/IDENTITY.md).
|
- `identity` (optional, core 0.7.0): the Domi identity's root key and the certs it issued (docs/IDENTITY.md);
|
||||||
|
since core 0.10.0 a cert may carry `revoked_at` and `revocation`.
|
||||||
An older Custos drops it when it saves, so every Custos that saves the vault must be 0.7.0 or later.
|
An older Custos drops it when it saves, so every Custos that saves the vault must be 0.7.0 or later.
|
||||||
- `folder` (optional item member, core 0.8.0): a list of folder names, outermost first (a KeePass group path,
|
- `folder` (optional item member, core 0.8.0): a list of folder names, outermost first (a KeePass group path,
|
||||||
docs/KDBX.md). Absent or empty = no folder.
|
docs/KDBX.md). Absent or empty = no folder.
|
||||||
@@ -128,6 +129,98 @@ UTF-8 JSON, held in zeroizing buffers while being encrypted or parsed:
|
|||||||
An older Custos drops `folder` and `attachments` when it saves.
|
An older Custos drops `folder` and `attachments` when it saves.
|
||||||
- `signing` (optional, core 0.9.0): signing keys for releases and the audit log of every signing request
|
- `signing` (optional, core 0.9.0): signing keys for releases and the audit log of every signing request
|
||||||
(docs/SIGNING.md). An older Custos drops it when it saves, so every Custos that saves the vault must be 0.9.0 or later.
|
(docs/SIGNING.md). An older Custos drops it when it saves, so every Custos that saves the vault must be 0.9.0 or later.
|
||||||
|
- `provision` (optional, core 0.11.0): the Provisio audit, every outcome of a server's *ask* or *offer* (the app's
|
||||||
|
docs/10_provisio.md). An older Custos ignores it when it reads and drops it when it saves, so every Custos that
|
||||||
|
saves the vault must be 0.11.0 or later. See "The provision audit" below.
|
||||||
|
- `security` (optional, core 0.12.0): the security level, the hardening checklist and their audit (the app's
|
||||||
|
docs/11_runs_and_levels.md). An older Custos ignores it when it reads and drops it when it saves (the level falls
|
||||||
|
back to Standard, the checklist to unticked), so every Custos that saves the vault must be 0.12.0 or later. See
|
||||||
|
"The security member" below.
|
||||||
|
|
||||||
|
**Values older cores refuse.** A reader refuses a file whose closed lists hold a value it does not know (see each
|
||||||
|
member), so these values, new in core 0.12.0, make a vault unreadable for a core before 0.12.0 once they are
|
||||||
|
written: a `signing` audit entry of kind `approval` (docs/SIGNING.md), a `provision` entry with store `display` or
|
||||||
|
outcome `confirmed`. A vault without them still opens in core 0.11.0.
|
||||||
|
|
||||||
|
### The provision audit (core 0.11.0)
|
||||||
|
|
||||||
|
```json
|
||||||
|
"provision": {
|
||||||
|
"audit": [
|
||||||
|
{ "at": 1793750100000, "direction": "offer", "host": "nixos-vm", "item": "fabrica/gitea-read-token",
|
||||||
|
"store": "vault", "run": "deploy-7", "kind": "Gitea token, read:repository", "code": "684361",
|
||||||
|
"outcome": "accepted", "replaced": true }
|
||||||
|
]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
| Member | |
|
||||||
|
| :-- | :-- |
|
||||||
|
| `at` | Unix milliseconds |
|
||||||
|
| `direction` | `ask` (the server asked for a secret) or `offer` (the server offered one) |
|
||||||
|
| `host` | the name the factor service gave, 1–253 characters `[A-Za-z0-9.-]` |
|
||||||
|
| `item` | `^[a-z0-9][a-z0-9._-]{0,63}(/[a-z0-9][a-z0-9._-]{0,63}){0,3}$`, as the factor service checks it |
|
||||||
|
| `store` | `vault`, `claude`, `cloud` or (core 0.12.0) `display`: shown once on the card, stored nowhere |
|
||||||
|
| `run` | optional, `[A-Za-z0-9._-]{1,64}` |
|
||||||
|
| `kind` | optional, at most 200 characters, no control characters (an offer's label; an ask's `--generate` recipe) |
|
||||||
|
| `code` | the match code: six ASCII digits |
|
||||||
|
| `outcome` | `approved`, `generated`, `accepted`, `refused`, `out-of-scope`, `invalid`, `expired` or (core 0.12.0) `confirmed` |
|
||||||
|
| `replaced` | `true` when an accepted offer replaced an existing item |
|
||||||
|
|
||||||
|
A **display offer** (core 0.12.0; a TOTP seed moved to a phone) is an `offer` with store `display`. Its outcome is
|
||||||
|
`confirmed` (Mark typed the phone's current code, Custos checked it and sent it to the server), `refused`, `expired`,
|
||||||
|
`invalid` or `out-of-scope`; never `accepted`, `approved` or `generated`, and never `replaced`, because nothing is
|
||||||
|
stored. `confirmed` belongs to display offers only. A code Custos's own check refuses stays on the card and is not
|
||||||
|
an outcome; a code the server then refuses (its exit 10) is not seen by Custos, so there is no `confirmed-wrong`.
|
||||||
|
|
||||||
|
- **No value, ever.** There is no member that holds a secret: every member is something the server sent in the
|
||||||
|
clear through the mailbox (host, item, store, run, kind) or derives from a public key (`code`). A recorded
|
||||||
|
entry is checked against the table above; an entry that does not fit is refused, not stored.
|
||||||
|
- **Append-only.** The API records an entry and lists them (oldest first); nothing edits or removes one, except
|
||||||
|
that the log keeps the newest 5 000 entries and drops the oldest beyond that.
|
||||||
|
- Readers ignore members of an entry they do not know. A file whose `provision` has an `outcome`, `direction` or
|
||||||
|
`store` this core does not know does not open (`Corrupted`), as for `signing`.
|
||||||
|
|
||||||
|
### The security member (core 0.12.0)
|
||||||
|
|
||||||
|
```json
|
||||||
|
"security": {
|
||||||
|
"setup": { "started": 1793750000000, "until": 1793757200000 },
|
||||||
|
"finished": 1793751000000,
|
||||||
|
"ticked": ["hello-approvals", "no-ssh"],
|
||||||
|
"keptScope": { "ask": ["arca/"], "offer": ["arca/", "fabrica/"] },
|
||||||
|
"audit": [
|
||||||
|
{ "at": 1793750000000, "action": "setup-started" },
|
||||||
|
{ "at": 1793751000000, "action": "setup-finished" },
|
||||||
|
{ "at": 1793752000000, "action": "ticked", "item": "no-ssh" },
|
||||||
|
{ "at": 1793753000000, "action": "unticked", "item": "no-ssh", "auth": "hello" }
|
||||||
|
]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
| Member | |
|
||||||
|
| :-- | :-- |
|
||||||
|
| `setup` | optional: the last Setup window, Unix milliseconds; `until` is 2 hours after `started` |
|
||||||
|
| `finished` | optional: when that window ended, by *Finish setup*, or `until` once its expiry was noticed |
|
||||||
|
| `ticked` | the checklist items that are ticked: `totp-on-phone`, `hello-approvals`, `narrow-scope`, `rotate-setup`, `no-ssh`, `phone-approves` |
|
||||||
|
| `keptScope` | optional: the server scope prefixes *Narrow the server scope* replaced (`ask`, `offer`: at most 64 each, 1–200 characters, no control characters), kept for its undo |
|
||||||
|
| `audit` | `{at, action, item?, auth?}`; `action` is `setup-started`, `setup-finished`, `setup-expired`, `ticked`, `unticked`, `ssh-connected` or `totp-moved`; `item` a checklist item (with `ticked`, `unticked`); `auth` is `hello` or `password` (with `unticked`) |
|
||||||
|
|
||||||
|
The **level** is computed, never stored:
|
||||||
|
|
||||||
|
- **Setup** while there is a `setup` window, it has not `finished`, and `started` ≤ now < `until`;
|
||||||
|
- otherwise **Hardened** when at least one item is ticked;
|
||||||
|
- otherwise **Standard** (also every vault without the member).
|
||||||
|
|
||||||
|
Ticked items hold during Setup too: Setup never undoes hardening. Starting Setup while in Setup changes nothing;
|
||||||
|
after a window ended a new one starts at now. Its expiry is written (`setup-expired`, and `finished` = `until`) by
|
||||||
|
the first change after it, not by reading.
|
||||||
|
|
||||||
|
- **Append-only** like `provision`: the API adds entries and lists them; the log keeps the newest 5 000.
|
||||||
|
- Absent while nothing was ever set, so a vault without it is written exactly as before.
|
||||||
|
- Readers ignore members they do not know. A file whose `security` has an item, action or auth this core does not
|
||||||
|
know, a window whose `until` is not after `started`, `finished` without `setup`, or a kept scope that breaks the
|
||||||
|
rules above does not open (`Corrupted`).
|
||||||
|
|
||||||
### Item types and their fields (v1)
|
### Item types and their fields (v1)
|
||||||
|
|
||||||
|
|||||||
+34
-5
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
Every Domi app gets its own subkey, certified by **one root Ed25519 key per person**. The root key lives in
|
Every Domi app gets its own subkey, certified by **one root Ed25519 key per person**. The root key lives in
|
||||||
the vault and never leaves it: no function of this crate returns it, and the vault signs nothing with it but
|
the vault and never leaves it: no function of this crate returns it, and the vault signs nothing with it but
|
||||||
subkey certificates. The certificate format, the match code and verification are in Fundamentum
|
subkey certificates and revocations of keys the person revoked. The certificate format, the match code and verification are in Fundamentum
|
||||||
(`crates/tessera`, `docs/TESSERA.md`); this page is the vault side.
|
(`crates/tessera`, `docs/TESSERA.md`); this page is the vault side.
|
||||||
|
|
||||||
## Creating it: the order is mandatory
|
## Creating it: the order is mandatory
|
||||||
@@ -31,6 +31,12 @@ is `Clone` or `Serialize`; each prints `[redacted]`.
|
|||||||
Test vector: entropy `00` × 32 → `abandon` × 23 + `art` → root public key
|
Test vector: entropy `00` × 32 → `abandon` × 23 + `art` → root public key
|
||||||
`vCrwX9p44un1ftQLgJtuaVQ0qPWbFfzNjgrlDkL4TKs` (base64url). Fundamentum pins the same value.
|
`vCrwX9p44un1ftQLgJtuaVQ0qPWbFfzNjgrlDkL4TKs` (base64url). Fundamentum pins the same value.
|
||||||
|
|
||||||
|
### Restoring it from the 24 words (core 0.10.0)
|
||||||
|
`Enrollment::restore(phrase)` takes the whole phrase, typed back, and gives a `Confirmed`: the person typed
|
||||||
|
all 24 words, which proves more than three. The words are checked against the BIP39 English list and its
|
||||||
|
checksum (any case, any spacing between them); anything else is `Error::NotAMnemonic`, which names no word.
|
||||||
|
The same words give the same root, so every app and every group trusts it again.
|
||||||
|
|
||||||
## In the vault file
|
## In the vault file
|
||||||
|
|
||||||
A body member next to `items` (docs/FORMAT.md, "Body"); old vaults without it open as before:
|
A body member next to `items` (docs/FORMAT.md, "Body"); old vaults without it open as before:
|
||||||
@@ -42,13 +48,19 @@ A body member next to `items` (docs/FORMAT.md, "Body"); old vaults without it op
|
|||||||
"created": 1793000000000,
|
"created": 1793000000000,
|
||||||
"issued": [
|
"issued": [
|
||||||
{ "kind": "app", "app_id": "fiscus", "purpose": "sync", "subkey": "<base64url>", "label": "fiscus.exe",
|
{ "kind": "app", "app_id": "fiscus", "purpose": "sync", "subkey": "<base64url>", "label": "fiscus.exe",
|
||||||
"not_before": 1793000000, "not_after": 1824536000, "issued": 1793000000000 }
|
"not_before": 1793000000, "not_after": 1824536000, "issued": 1793000000000,
|
||||||
|
"revoked_at": 1795000000, "revocation": ["<base64url TRV1>"] }
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
- `issued` records each cert the vault signed, for *Domi identity → apps and devices*. It is a record, not
|
- `issued` records each cert the vault signed, for *Domi identity → apps and devices*. It is a record, not
|
||||||
a trust list: revocation is v1.1.
|
a trust list.
|
||||||
|
- `revoked_at` (Unix seconds, core 0.10.0) is set when the person revokes the key; `revocation` holds the
|
||||||
|
signed statements once they exist. Both are left out until then. A renewed key has several certs: all of
|
||||||
|
them are marked.
|
||||||
|
- **A Custos older than core 0.10.0 drops `revoked_at` and `revocation` when it saves the vault**, so a
|
||||||
|
revocation in progress would have to be started again.
|
||||||
- **An older Custos drops the member when it saves the vault** (it ignores members it does not know). Every
|
- **An older Custos drops the member when it saves the vault** (it ignores members it does not know). Every
|
||||||
Custos that saves this vault must run core 0.7.0 or later. The mnemonic recovers the root either way.
|
Custos that saves this vault must run core 0.7.0 or later. The mnemonic recovers the root either way.
|
||||||
|
|
||||||
@@ -59,9 +71,26 @@ A body member next to `items` (docs/FORMAT.md, "Body"); old vaults without it op
|
|||||||
| `Vault::domi_root_public()` | the root public key, if there is an identity |
|
| `Vault::domi_root_public()` | the root public key, if there is an identity |
|
||||||
| `Vault::domi_sign_cert(tbs)` | Ed25519 over `"tessera cert v1\0" ‖ tbs`. Refuses a `tbs` that does not start with `TSC1` followed by this root's public key |
|
| `Vault::domi_sign_cert(tbs)` | Ed25519 over `"tessera cert v1\0" ‖ tbs`. Refuses a `tbs` that does not start with `TSC1` followed by this root's public key |
|
||||||
| `Vault::domi_issued()`, `domi_record(issued)` | the record of issued certs |
|
| `Vault::domi_issued()`, `domi_record(issued)` | the record of issued certs |
|
||||||
|
| `Vault::domi_mark_revoked(subkey, at)` | the person revoked this key: marks every cert of it, returns the time in effect (the first one, if it was marked before) |
|
||||||
|
| `Vault::domi_sign_revocation(tbs)` | Ed25519 over `"tessera revoke v1\0" ‖ tbs`. Refuses a `tbs` that does not start with `TRV1`, this root's public key, a key marked revoked and that key's `revoked_at` |
|
||||||
|
| `Vault::domi_record_revocation(subkey, statements)` | keeps the signed statements with the key's certs |
|
||||||
|
| `Vault::domi_backup_secret(app_id)` | the app's backup secret (below) |
|
||||||
|
|
||||||
The prefix check means the vault is not a general signing oracle: whatever the app hands it, the result
|
The prefix checks mean the vault is not a general signing oracle: whatever the app hands it, the result
|
||||||
can only ever verify as a certificate naming this root.
|
can only ever verify as a certificate naming this root, or as a revocation of a key the person revoked, at
|
||||||
|
the time they did. The two domains differ, so neither can pass for the other. Statement format: Fundamentum
|
||||||
|
docs/TESSERA.md §12.
|
||||||
|
|
||||||
|
### The backup secret (core 0.10.0)
|
||||||
|
```
|
||||||
|
backup secret = HKDF-SHA256(salt = "tessera backup v1", ikm = the root secret, info = app id)
|
||||||
|
```
|
||||||
|
Custos hands an app its own (Domi pipe `backup_key`, behind the app's namespace grant); the app seals its
|
||||||
|
backup with it and names its backup mailbox from it (Fundamentum docs/TESSERA.md §12). It comes back from
|
||||||
|
the 24 words alone. The caller passes a valid app id (a-z, 0-9, `-`). Test vector, shared with Fundamentum:
|
||||||
|
the zero-entropy root, app `fiscus` → `HKDF-Expand(secret, "mailbox")` =
|
||||||
|
`IygCOrh-ibO6-KY5AXQ9Prl2SyPWQIyZZ-anffcbMCU`, and XChaCha20-Poly1305 with
|
||||||
|
`HKDF-Expand(secret, "seal")`, a zero nonce and empty input = `ci_JRbtsx5prR83KT9Y7LA` (the tag).
|
||||||
|
|
||||||
## What it does not protect
|
## What it does not protect
|
||||||
|
|
||||||
|
|||||||
+23
-2
@@ -20,8 +20,29 @@ aad "CSL1" ‖ E ‖ context
|
|||||||
A box opens only with the context it was sealed for, so a box for one request does not work as another.
|
A box opens only with the context it was sealed for, so a box for one request does not work as another.
|
||||||
- **A low-order public key is refused** on both sides: the shared secret must be contributory.
|
- **A low-order public key is refused** on both sides: the shared secret must be contributory.
|
||||||
- **Plaintext limit:** 32 KiB.
|
- **Plaintext limit:** 32 KiB.
|
||||||
- **The recipient's secret half** lives only in memory, as `x25519_dalek::StaticSecret` with `zeroize`,
|
- **The recipient's secret half** lives in memory as `x25519_dalek::StaticSecret` with `zeroize`, and is
|
||||||
and is wiped on drop. Nothing writes it to disk.
|
wiped on drop. One-time keys (`Recipient::generate`) are the default and nothing writes them to disk.
|
||||||
|
|
||||||
|
### A kept key (core 0.11.0)
|
||||||
|
|
||||||
|
The recipient's secret may now be kept by the caller, for one purpose: the PC's Provisio sealing key
|
||||||
|
(docs/10_provisio.md in the app), the key the server seals **offers** to. Custos makes it once with
|
||||||
|
`Recipient::generate`, keeps `Recipient::secret_bytes()` DPAPI-sealed in `<data>actors\provision.key`, and
|
||||||
|
restores it with `Recipient::from_secret` at every start. Everything else (approvals, pairing, a Provisio *ask*)
|
||||||
|
still uses a fresh one-time key per request.
|
||||||
|
|
||||||
|
```
|
||||||
|
Recipient::from_secret(Zeroizing<[u8; 32]>) -> Result<Recipient, SealError> // BadKey for a known key
|
||||||
|
Recipient::secret_bytes(&self) -> Zeroizing<[u8; 32]> // only for a key that is kept
|
||||||
|
```
|
||||||
|
|
||||||
|
- `from_secret` refuses (`BadKey`) a secret that X25519 clamps to zero (all zeros: a wiped or never-filled
|
||||||
|
buffer) and, as for public keys, one whose shared secrets would not be contributory.
|
||||||
|
- A kept key opens every box ever sealed to it, so the **context** carries the binding: an offer is sealed for
|
||||||
|
`provision-offer:<store>:<item>`, and the PC checks the plaintext's item, store, kind and code key against the
|
||||||
|
offer before it shows a card. The mailbox refuses an offer whose ephemeral key it has seen (replay).
|
||||||
|
- `secret_bytes` hands out the secret in a `Zeroizing` buffer. It goes to the caller's sealed storage and
|
||||||
|
nowhere else: never a log, a message or a file in the clear. `Debug` of a `Recipient` prints `[redacted]`.
|
||||||
|
|
||||||
## The match code
|
## The match code
|
||||||
|
|
||||||
|
|||||||
+63
-9
@@ -1,4 +1,4 @@
|
|||||||
# Signing keys (core 0.9.0)
|
# Signing keys (core 0.9.0; deploy approvals 0.12.0)
|
||||||
|
|
||||||
Custos signs releases for Fabrica Domi · Artifex without a private key ever leaving the vault. A build asks for a
|
Custos signs releases for Fabrica Domi · Artifex without a private key ever leaving the vault. A build asks for a
|
||||||
signature over a **digest**; Custos checks who may ask, Mark approves with a match code, and the vault signs and
|
signature over a **digest**; Custos checks who may ask, Mark approves with a match code, and the vault signs and
|
||||||
@@ -18,12 +18,16 @@ In the vault body, next to `identity` (FORMAT.md), as the optional member `signi
|
|||||||
"secret": "<base64>", "cert": "<base64 DER>", "created": 1793750000000, "pipelines": [], "repos": [] },
|
"secret": "<base64>", "cert": "<base64 DER>", "created": 1793750000000, "pipelines": [], "repos": [] },
|
||||||
{ "id": "domi-code-signing", "kind": "code-signing", "role": "release", "name": "Domi Code Signing",
|
{ "id": "domi-code-signing", "kind": "code-signing", "role": "release", "name": "Domi Code Signing",
|
||||||
"secret": "<base64>", "cert": "<base64 DER>", "issuer": "domi-root", "created": 1793750000000,
|
"secret": "<base64>", "cert": "<base64 DER>", "issuer": "domi-root", "created": 1793750000000,
|
||||||
"pipelines": ["release"], "repos": ["Arca"] }
|
"pipelines": ["release"], "repos": ["Arca"] },
|
||||||
|
{ "id": "domi-approve", "kind": "ed25519", "role": "release", "name": "Domi deploy approval",
|
||||||
|
"secret": "<base64>", "public": "<base64>", "keyId": "<16 hex>", "created": 1793750000000,
|
||||||
|
"pipelines": ["release"], "repos": ["Arca", "Fabrica"] }
|
||||||
],
|
],
|
||||||
"audit": [
|
"audit": [
|
||||||
{ "at": 1793750100000, "key": "domi-release", "kind": "minisign", "outcome": "approved", "via": "local",
|
{ "at": 1793750100000, "key": "domi-release", "kind": "minisign", "outcome": "approved", "via": "local",
|
||||||
"repo": "Arca", "commit": "6925d0cb08b9…", "pipeline": "release", "step": "sign", "trigger": "tag",
|
"repo": "Arca", "commit": "6925d0cb08b9…", "pipeline": "release", "step": "sign", "trigger": "tag",
|
||||||
"file": "Arca_0.1.0_x64-setup.exe", "size": 25145977, "sha256": "c4995c6e…", "signature": "<sha256 hex>" }
|
"file": "Arca_0.1.0_x64-setup.exe", "size": 25145977, "sha256": "c4995c6e…", "signature": "<sha256 hex>",
|
||||||
|
"run": "r-42", "version": "0.1.0" }
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
@@ -39,11 +43,14 @@ vault must be 0.9.0 or later. There is no mnemonic for these keys: back the vaul
|
|||||||
|
|
||||||
| `kind` | Key | Signs | Created |
|
| `kind` | Key | Signs | Created |
|
||||||
| :-- | :-- | :-- | :-- |
|
| :-- | :-- | :-- | :-- |
|
||||||
| `ed25519` | Ed25519; `secret` is the 32-byte seed, `public` the 32-byte key, `keyId` minisign's 8-byte key id | `minisign`, `manifest` | random |
|
| `ed25519` | Ed25519; `secret` is the 32-byte seed, `public` the 32-byte key, `keyId` minisign's 8-byte key id | `minisign`, `manifest`; `domi-approve` only `approval` | random |
|
||||||
| `root-ca` | RSA-3072; `secret` is PKCS#8 DER; `cert` a self-signed X.509 v3 CA certificate, valid 10 years | only the leaf it issues, at creation; never a request | random |
|
| `root-ca` | RSA-3072; `secret` is PKCS#8 DER; `cert` a self-signed X.509 v3 CA certificate, valid 10 years | only the leaf it issues, at creation; never a request | random |
|
||||||
| `code-signing` | RSA-3072; `secret` PKCS#8 DER; `cert` an X.509 v3 leaf issued by `issuer`, valid 2 years, EKU code signing | `authenticode` | random |
|
| `code-signing` | RSA-3072; `secret` PKCS#8 DER; `cert` an X.509 v3 leaf issued by `issuer`, valid 2 years, EKU code signing | `authenticode` | random |
|
||||||
|
|
||||||
`role` is `release` or `test`. *Create release keys* makes `domi-release`, `domi-root` and `domi-code-signing`.
|
`role` is `release` or `test`. *Create release keys* makes `domi-release`, `domi-root`, `domi-code-signing` and
|
||||||
|
(since core 0.12.0) `domi-approve` ("Domi deploy approval"), the Ed25519 key that signs deploy approvals, with the
|
||||||
|
release keys' scope. A vault whose release keys were made by an older core gets it with `signing_add_approve`
|
||||||
|
(*Create approval key*).
|
||||||
*Create test keys* makes `domi-test` (Ed25519) and `domi-test-code-signing`, a leaf issued by its own
|
*Create test keys* makes `domi-test` (Ed25519) and `domi-test-code-signing`, a leaf issued by its own
|
||||||
`domi-test-root`: a test certificate never chains to the household root, so an automatically approved signature is
|
`domi-test-root`: a test certificate never chains to the household root, so an automatically approved signature is
|
||||||
never trusted by Mark's PCs.
|
never trusted by Mark's PCs.
|
||||||
@@ -69,6 +76,11 @@ A request names a key, a kind and what to sign. Custos never receives the file.
|
|||||||
| `minisign` | `digest`: BLAKE2b-512 of the file (64 bytes) | a `.minisig` file (prehashed, `ED`) |
|
| `minisign` | `digest`: BLAKE2b-512 of the file (64 bytes) | a `.minisig` file (prehashed, `ED`) |
|
||||||
| `manifest` | `manifest`: the `SHA256SUMS` text itself (≤ 32 KiB, canonical, see below) | a `.minisig` file over it |
|
| `manifest` | `manifest`: the `SHA256SUMS` text itself (≤ 32 KiB, canonical, see below) | a `.minisig` file over it |
|
||||||
| `authenticode` | `digest`: the 32-byte SHA-256 in signtool's `.dig` | the RSA PKCS#1 v1.5 signature (384 bytes) for `.dig.signed` |
|
| `authenticode` | `digest`: the 32-byte SHA-256 in signtool's `.dig` | the RSA PKCS#1 v1.5 signature (384 bytes) for `.dig.signed` |
|
||||||
|
| `approval` | `approval`: a deploy approval's canonical JSON (at most 8 KiB, see below), and `run` | a `.minisig` file over it |
|
||||||
|
|
||||||
|
Any request may carry a `run` (`[A-Za-z0-9._-]{1,64}`, core 0.12.0): the build's run id, so the app can show every
|
||||||
|
request of one run on one card. It is kept in the audit entry. A malformed `run` is `invalid`; `approval` text on a
|
||||||
|
request of another kind is `invalid` too.
|
||||||
|
|
||||||
### minisign
|
### minisign
|
||||||
|
|
||||||
@@ -96,6 +108,40 @@ the whole minisign text. That wrapping is the build's job.
|
|||||||
sorted by their UTF-8 bytes, no empty file. Custos checks the form, hashes the text itself and signs it as `minisign`
|
sorted by their UTF-8 bytes, no empty file. Custos checks the form, hashes the text itself and signs it as `minisign`
|
||||||
(file name `SHA256SUMS`). A text in any other form is refused, not normalised.
|
(file name `SHA256SUMS`). A text in any other form is refused, not normalised.
|
||||||
|
|
||||||
|
### approval (core 0.12.0)
|
||||||
|
|
||||||
|
A deploy approval says "this run of this commit may deploy to these targets until then". Fabrica's hub checks it with
|
||||||
|
`domi-approve`'s public key before it runs a deploy step. What is signed is one line of JSON, no spaces, the keys in
|
||||||
|
exactly this order:
|
||||||
|
|
||||||
|
```
|
||||||
|
{"v":1,"run":"r-42","repo":"Arca","commit":"<40 hex>","pipeline":"release","version":"0.7.0","targets":["deploy to nixos-vm","publish to Aula"],"expires":1793000000}
|
||||||
|
```
|
||||||
|
|
||||||
|
| Key | |
|
||||||
|
| :-- | :-- |
|
||||||
|
| `v` | `1` |
|
||||||
|
| `run` | `[A-Za-z0-9._-]{1,64}`, equal to the request's `run` |
|
||||||
|
| `repo`, `pipeline`, `version` | 1–64 of `[A-Za-z0-9._+-]` |
|
||||||
|
| `commit` | 40 lower-case hex digits |
|
||||||
|
| `targets` | 1–16 strings of 1–80 characters (Unicode scalar values); no control characters, and none of the invisible ones that change how a line looks on the card (U+00AD, U+061C, U+180E, U+200B–U+200F, U+2028–U+202E, U+2060–U+2069, U+FEFF) |
|
||||||
|
| `expires` | Unix seconds, later than now and at most 3 600 s after now (checked before the card and again when signing) |
|
||||||
|
|
||||||
|
Strings use JSON's minimal escaping: a quote is written `\"`, a backslash `\\`, every other character as
|
||||||
|
itself (no `\u` escapes, no `\/`; control characters cannot occur). There is no newline at the end. Custos
|
||||||
|
parses the text, writes it again in this form and refuses anything that is not byte-identical (`invalid`): another
|
||||||
|
key order, a space, an escape, a duplicate or unknown key, a number written as `1.0`.
|
||||||
|
|
||||||
|
The signature is a prehashed minisign signature over those bytes, made exactly as for `minisign` with the file name
|
||||||
|
`approval-<run>.json`, so the trusted comment is `timestamp:<now>\tfile:approval-<run>.json\thashed`
|
||||||
|
(the `hashed` that minisign itself writes for a prehashed signature). `minisign -V -P <domi-approve public key> -m
|
||||||
|
approval.json` verifies it.
|
||||||
|
|
||||||
|
`domi-approve` signs only `approval`, and `approval` is signed only by `domi-approve`; it is a release key, so it
|
||||||
|
always asks. The scope is checked against the JSON's `repo` and `pipeline`; a request whose context names another
|
||||||
|
`repo`, `pipeline`, `commit` or `version` than its JSON is `invalid` (an empty context member is filled from the JSON
|
||||||
|
in the audit). The audit entry's `file` is `approval-<run>.json`.
|
||||||
|
|
||||||
### authenticode
|
### authenticode
|
||||||
|
|
||||||
The file is signed by Windows' own tools in three steps, so the key stays in Custos:
|
The file is signed by Windows' own tools in three steps, so the key stays in Custos:
|
||||||
@@ -124,20 +170,28 @@ one entry, whatever happened:
|
|||||||
| `refused` | Mark refused |
|
| `refused` | Mark refused |
|
||||||
| `expired` | nobody answered within 5 minutes |
|
| `expired` | nobody answered within 5 minutes |
|
||||||
| `out-of-scope` | the pipeline or repo is not on the key's lists (whether or not it was approved) |
|
| `out-of-scope` | the pipeline or repo is not on the key's lists (whether or not it was approved) |
|
||||||
| `invalid` | the request was malformed (wrong digest length, a manifest not in canonical form, a kind the key cannot do) |
|
| `invalid` | the request was malformed (wrong digest length, a manifest or approval not in canonical form, an expired approval, a kind the key cannot do) |
|
||||||
|
|
||||||
`signature` is the SHA-256 (hex) of what was returned, for the signed outcomes. `via` is `local` (the Domi pipe) or
|
`signature` is the SHA-256 (hex) of what was returned, for the signed outcomes. `via` is `local` (the Domi pipe) or
|
||||||
`remote` (the factor service's mailbox). The entry is part of the vault, so it survives a reopen and travels with it.
|
`remote` (the factor service's mailbox). `run` (core 0.12.0) is the request's run, absent without one; `version`
|
||||||
|
(core 0.12.0) is the context's version, absent when empty. The entry is part of the vault, so it survives a reopen
|
||||||
|
and travels with it.
|
||||||
|
|
||||||
|
**Compatibility.** Older cores ignore `run`, `version` and the `domi-approve` key. An audit entry of kind
|
||||||
|
`approval` is a value they do not know, so a core before 0.12.0 refuses a vault that holds one (`Corrupted`): once a
|
||||||
|
vault has recorded an approval request, every Custos that opens it must be on core 0.12.0 or later.
|
||||||
|
|
||||||
## The API (custos-vault)
|
## The API (custos-vault)
|
||||||
|
|
||||||
```
|
```
|
||||||
Vault::signing_create(role, pipelines, repos, now) -> ids // release or test set
|
Vault::signing_create(role, pipelines, repos, now) -> ids // release (with domi-approve) or test set
|
||||||
|
Vault::signing_add_approve(now) -> "domi-approve" // for release keys made before 0.12.0
|
||||||
Vault::signing_keys() -> [SigningKeyView] // public parts only
|
Vault::signing_keys() -> [SigningKeyView] // public parts only
|
||||||
Vault::signing_set_scope(id, pipelines, repos)
|
Vault::signing_set_scope(id, pipelines, repos)
|
||||||
Vault::signing_export_cert(id) -> DER // a certificate, never a key
|
Vault::signing_export_cert(id) -> DER // a certificate, never a key
|
||||||
Vault::signing_minisign_public(id) -> minisign.pub text
|
Vault::signing_minisign_public(id) -> minisign.pub text
|
||||||
Vault::signing_check(&request) -> Ok | Refusal // before asking Mark
|
Vault::signing_check(&request) -> Ok | Refusal // before asking Mark (the clock: now_ms)
|
||||||
|
Vault::signing_check_at(&request, now) -> Ok | Refusal // the same at `now` (an approval's expiry)
|
||||||
Vault::signing_sign(&request, Approval::{Mark, Auto}, now) -> Signed // checks again, signs, records
|
Vault::signing_sign(&request, Approval::{Mark, Auto}, now) -> Signed // checks again, signs, records
|
||||||
Vault::signing_refuse(&request, outcome, now) // records refused / expired
|
Vault::signing_refuse(&request, outcome, now) // records refused / expired
|
||||||
Vault::signing_audit() -> [AuditEntry]
|
Vault::signing_audit() -> [AuditEntry]
|
||||||
|
|||||||
Reference in New Issue
Block a user