[team] Team vaults: member keys, member slots (kind 6), policies per environment, the canonical sign.request, approval statements, policy proofs; cosign and Tauri updater envelopes; v0.18.0
This commit is contained in:
@@ -22,9 +22,12 @@ bip39 = { version = "2", default-features = false, features = ["std", "zeroize"]
|
||||
ed25519-dalek = { version = "2", default-features = false, features = ["std", "zeroize"] }
|
||||
# Signing keys for releases (docs/SIGNING.md).
|
||||
custos-sign = { path = "../custos-sign" }
|
||||
# Team vaults (docs/TEAM.md, core 0.18.0).
|
||||
custos-team = { path = "../custos-team" }
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = "3"
|
||||
custos-seal = { path = "../custos-seal" }
|
||||
minisign-verify = "0.3"
|
||||
rsa = { version = "0.9", features = ["sha2"] }
|
||||
sha2-010 = { package = "sha2", version = "0.10", features = ["oid"] }
|
||||
|
||||
@@ -18,6 +18,12 @@ pub const SLOT_SINGLE: u8 = 4;
|
||||
/// The recovery key's slot (core 0.17.0; docs/FACTORS.md, "The recovery key").
|
||||
pub const SLOT_RECOVERY: u8 = 5;
|
||||
pub const RECOVERY_ID_LEN: usize = 4;
|
||||
/// A team vault's member slot (core 0.18.0; docs/TEAM.md): the team key sealed to one member.
|
||||
pub const SLOT_MEMBER: u8 = 6;
|
||||
/// team id (16) ‖ member id (16) ‖ epoch (4) ‖ sealed team key (108).
|
||||
pub const MEMBER_SLOT_LEN: usize = 16 + 16 + 4 + 108;
|
||||
/// A team has at most this many members.
|
||||
pub const MAX_MEMBER_SLOTS: usize = 32;
|
||||
const KDF_ARGON2ID: u8 = 1;
|
||||
pub const SALT_LEN: usize = 32;
|
||||
pub const ID_LEN: usize = 16;
|
||||
@@ -289,6 +295,38 @@ impl RecoverySlot {
|
||||
}
|
||||
}
|
||||
|
||||
/// A team vault's member slot (kind 6): the box carries its own binding (its context names team, epoch and member).
|
||||
#[derive(Clone)]
|
||||
pub struct MemberSlot {
|
||||
pub team: [u8; ID_LEN],
|
||||
pub member: [u8; ID_LEN],
|
||||
pub epoch: u32,
|
||||
pub sealed: Vec<u8>,
|
||||
}
|
||||
|
||||
impl MemberSlot {
|
||||
pub fn raw(&self) -> RawSlot {
|
||||
let mut p = Vec::with_capacity(MEMBER_SLOT_LEN);
|
||||
p.extend_from_slice(&self.team);
|
||||
p.extend_from_slice(&self.member);
|
||||
p.extend_from_slice(&self.epoch.to_le_bytes());
|
||||
p.extend_from_slice(&self.sealed);
|
||||
RawSlot { kind: SLOT_MEMBER, payload: p }
|
||||
}
|
||||
|
||||
pub fn parse(payload: &[u8]) -> Result<Self, Error> {
|
||||
if payload.len() != MEMBER_SLOT_LEN {
|
||||
return Err(Error::Malformed);
|
||||
}
|
||||
Ok(MemberSlot {
|
||||
team: payload[..16].try_into().unwrap(),
|
||||
member: payload[16..32].try_into().unwrap(),
|
||||
epoch: u32::from_le_bytes(payload[32..36].try_into().unwrap()),
|
||||
sealed: payload[36..].to_vec(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Header {
|
||||
pub version: u16,
|
||||
pub slots: Vec<RawSlot>,
|
||||
@@ -348,6 +386,9 @@ impl Header {
|
||||
|
||||
/// Structural rules of a v2 header (docs/FACTORS.md, "Limits a reader enforces").
|
||||
fn check_v2(&self) -> Result<(), Error> {
|
||||
if self.slots.iter().any(|s| s.kind == SLOT_MEMBER) {
|
||||
return self.check_team();
|
||||
}
|
||||
let mut ids = Vec::new();
|
||||
for s in self.slots.iter().filter(|s| s.kind == SLOT_FACTOR) {
|
||||
ids.push(FactorSlot::parse(&s.payload)?.id);
|
||||
@@ -398,6 +439,31 @@ impl Header {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A team vault (docs/TEAM.md): 1 ..= 32 member slots and nothing else, one team id and epoch, distinct members.
|
||||
fn check_team(&self) -> Result<(), Error> {
|
||||
if self.slots.len() > MAX_MEMBER_SLOTS || self.slots.iter().any(|s| s.kind != SLOT_MEMBER) {
|
||||
return Err(Error::Malformed);
|
||||
}
|
||||
let slots = self.slots.iter().map(|s| MemberSlot::parse(&s.payload)).collect::<Result<Vec<_>, _>>()?;
|
||||
let first = &slots[0];
|
||||
let mut members: Vec<[u8; ID_LEN]> = Vec::with_capacity(slots.len());
|
||||
for s in &slots {
|
||||
if s.team != first.team || s.epoch != first.epoch || members.contains(&s.member) {
|
||||
return Err(Error::Malformed);
|
||||
}
|
||||
members.push(s.member);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn is_team(&self) -> bool {
|
||||
self.slots.iter().any(|s| s.kind == SLOT_MEMBER)
|
||||
}
|
||||
|
||||
pub fn member_slots(&self) -> Vec<MemberSlot> {
|
||||
self.slots.iter().filter(|s| s.kind == SLOT_MEMBER).filter_map(|s| MemberSlot::parse(&s.payload).ok()).collect()
|
||||
}
|
||||
|
||||
pub fn factor_slots(&self) -> Vec<FactorSlot> {
|
||||
self.slots.iter().filter(|s| s.kind == SLOT_FACTOR).filter_map(|s| FactorSlot::parse(&s.payload).ok()).collect()
|
||||
}
|
||||
|
||||
@@ -27,11 +27,16 @@ mod save;
|
||||
mod secret;
|
||||
pub mod security;
|
||||
pub mod signing;
|
||||
pub mod team;
|
||||
|
||||
pub use item::{Attachment, Field, HISTORY_LIMIT, HistoryEntry, Item, ItemType, new_id, now_ms};
|
||||
pub use recovery::RecoveryKey;
|
||||
pub use save::{CrashPoint, save_atomic, save_atomic_crashing};
|
||||
pub use secret::{SecretBytes, SecretString};
|
||||
pub use team::{
|
||||
KnownTeam, NewSigner, NewTarget, Removal, RemovedMember, SignerView, TargetView, TeamAction, TeamAuditEntry,
|
||||
TeamMember, TeamView,
|
||||
};
|
||||
|
||||
use crypto::KEY_LEN;
|
||||
use format::{
|
||||
@@ -97,6 +102,15 @@ pub enum Error {
|
||||
Security(&'static str),
|
||||
#[error("signing keys: {0}")]
|
||||
Signing(String),
|
||||
/// A team vault operation was refused (docs/TEAM.md); names why, never a value.
|
||||
#[error("team: {0}")]
|
||||
Team(String),
|
||||
#[error("this is not a team vault")]
|
||||
NotATeam,
|
||||
#[error("this member key does not open this team vault: not a member, or removed")]
|
||||
NotAMember,
|
||||
#[error("this team vault is older than the one this member has seen, or another team's under the same id")]
|
||||
TeamRollback,
|
||||
#[error("{0}")]
|
||||
Io(#[from] std::io::Error),
|
||||
}
|
||||
@@ -295,6 +309,14 @@ struct Body {
|
||||
provision: Option<provision::ProvisionJson>,
|
||||
#[serde(default)]
|
||||
security: Option<security::State>,
|
||||
/// `"team"` for a team vault (core 0.18.0, docs/TEAM.md).
|
||||
#[serde(default)]
|
||||
kind: Option<String>,
|
||||
#[serde(default)]
|
||||
team: Option<team::TeamJson>,
|
||||
/// A person's member key (core 0.18.0).
|
||||
#[serde(default)]
|
||||
member: Option<team::MemberJson>,
|
||||
}
|
||||
|
||||
/// What `to_bytes` serializes: borrows the items instead of cloning every secret.
|
||||
@@ -312,6 +334,12 @@ struct BodyRef<'a> {
|
||||
provision: Option<provision::ProvisionJson>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
security: Option<security::State>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
kind: Option<&'static str>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
team: Option<team::TeamJson>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
member: Option<team::MemberJson>,
|
||||
}
|
||||
|
||||
/// An unlocked vault: the vault key and the decrypted items, both wiped on drop.
|
||||
@@ -332,6 +360,10 @@ pub struct Vault {
|
||||
provision: Vec<provision::ProvisionEntry>,
|
||||
/// The security level's Setup window, the checklist and their audit (docs/FORMAT.md).
|
||||
security: security::State,
|
||||
/// A team vault's own state (docs/TEAM.md); `None` for every other vault.
|
||||
team: Option<team::TeamState>,
|
||||
/// A person's member key and the teams it has opened (docs/TEAM.md); never in a team vault.
|
||||
member: Option<team::MemberState>,
|
||||
}
|
||||
|
||||
impl fmt::Debug for Vault {
|
||||
@@ -419,6 +451,24 @@ fn unwrap_factor(header: &Header, u: &Unlock) -> Result<FactorRec, Error> {
|
||||
}
|
||||
|
||||
impl Vault {
|
||||
/// An empty version-2 vault with `key` and no slots yet: a team vault writes its member slots itself.
|
||||
pub(crate) fn empty_v2(key: Zeroizing<[u8; KEY_LEN]>) -> Vault {
|
||||
Vault {
|
||||
key,
|
||||
version: VERSION_2,
|
||||
slots: Vec::new(),
|
||||
items: Vec::new(),
|
||||
factors: Vec::new(),
|
||||
kdf_new: KdfParams::DEFAULT,
|
||||
identity: None,
|
||||
signing: signing::Store::default(),
|
||||
provision: Vec::new(),
|
||||
security: security::State::default(),
|
||||
team: None,
|
||||
member: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// A new, empty version-1 vault with a fresh random vault key wrapped by `password`.
|
||||
pub fn create(password: &SecretString, kdf: KdfParams) -> Result<Vault, Error> {
|
||||
let key = crypto::random_key();
|
||||
@@ -434,6 +484,8 @@ impl Vault {
|
||||
signing: signing::Store::default(),
|
||||
provision: Vec::new(),
|
||||
security: security::State::default(),
|
||||
team: None,
|
||||
member: None,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -453,6 +505,8 @@ impl Vault {
|
||||
signing: signing::Store::default(),
|
||||
provision: Vec::new(),
|
||||
security: security::State::default(),
|
||||
team: None,
|
||||
member: None,
|
||||
};
|
||||
v.add_factor(a, label_a)?;
|
||||
v.add_factor(b, label_b)?;
|
||||
@@ -488,6 +542,8 @@ impl Vault {
|
||||
signing: signing::Store::default(),
|
||||
provision: Vec::new(),
|
||||
security: security::State::default(),
|
||||
team: None,
|
||||
member: None,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -614,6 +670,17 @@ impl Vault {
|
||||
None => signing::Store::default(),
|
||||
};
|
||||
let security = security::State::from_json(body.security).ok_or(Error::Corrupted)?;
|
||||
// A team vault (member slots) has a team body and nothing of a person's; every other vault has none.
|
||||
let team = match (header.is_team(), body.kind.as_deref(), body.team) {
|
||||
(true, Some("team"), Some(j)) => Some(team::TeamState::from_json(j).ok_or(Error::Corrupted)?),
|
||||
(false, None, None) => None,
|
||||
_ => return Err(Error::Corrupted),
|
||||
};
|
||||
let member = match body.member {
|
||||
Some(_) if team.is_some() => return Err(Error::Corrupted),
|
||||
Some(j) => Some(team::MemberState::from_json(j).ok_or(Error::Corrupted)?),
|
||||
None => None,
|
||||
};
|
||||
Ok(Vault {
|
||||
key,
|
||||
version: header.version,
|
||||
@@ -625,6 +692,8 @@ impl Vault {
|
||||
signing,
|
||||
provision: provision::from_json(body.provision),
|
||||
security,
|
||||
team,
|
||||
member,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -662,6 +731,9 @@ impl Vault {
|
||||
signing: self.signing.json(),
|
||||
provision: provision::json(&self.provision),
|
||||
security: self.security.json(),
|
||||
kind: self.team.is_some().then_some("team"),
|
||||
team: self.team.as_ref().map(team::TeamState::json),
|
||||
member: self.member.as_ref().map(team::MemberState::json),
|
||||
};
|
||||
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);
|
||||
|
||||
@@ -51,6 +51,8 @@ pub enum KeyKind {
|
||||
CodeSigning,
|
||||
/// An Android app's signing key (core 0.14.0): RSA-4096 and a self-signed certificate; signs `apk` only.
|
||||
Android,
|
||||
/// A team's cosign key (core 0.18.0, docs/TEAM.md): ECDSA P-256; signs `cosign` only, in a team vault only.
|
||||
EcdsaP256,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
@@ -64,6 +66,12 @@ pub enum SignKind {
|
||||
/// APK Signature Scheme v2/v3: 1 to 4 SHA-512 digests, signed with RSA PKCS#1 v1.5, by an Android key only
|
||||
/// (core 0.14.0).
|
||||
Apk,
|
||||
/// Tauri's updater: minisign over a BLAKE2b-512 digest, wrapped in base64 (core 0.18.0, team vaults only).
|
||||
#[serde(rename = "tauri-updater")]
|
||||
TauriUpdater,
|
||||
/// A cosign container image signature: ECDSA P-256 over the simple-signing payload (core 0.18.0, team vaults
|
||||
/// only).
|
||||
Cosign,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
@@ -153,6 +161,18 @@ pub struct AuditEntry {
|
||||
/// 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 team vault's entry (core 0.18.0, docs/TEAM.md): the member whose Custos signed or refused.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub by: Option<String>,
|
||||
/// The environment the request was for.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub env: Option<String>,
|
||||
/// The request hash (hex).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub request: Option<String>,
|
||||
/// The members whose approvals counted.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub approvers: Vec<String>,
|
||||
}
|
||||
|
||||
/// A standing approval (core 0.16.0, docs/SIGNING.md): what Mark allowed for good, when, and how often it was used.
|
||||
@@ -212,26 +232,29 @@ pub struct KeyView {
|
||||
/// The certificate (DER), for root, code-signing and Android keys.
|
||||
pub cert: Option<Vec<u8>>,
|
||||
pub issuer: Option<String>,
|
||||
/// The `cosign.pub` PEM, for ECDSA P-256 keys (core 0.18.0).
|
||||
pub public_pem: Option<String>,
|
||||
}
|
||||
|
||||
enum Secret {
|
||||
pub(crate) enum Secret {
|
||||
Ed25519(Ed25519Secret),
|
||||
Rsa(RsaSecret),
|
||||
P256(custos_sign::P256Secret),
|
||||
}
|
||||
|
||||
struct Key {
|
||||
id: String,
|
||||
kind: KeyKind,
|
||||
role: Role,
|
||||
name: String,
|
||||
secret: Secret,
|
||||
public: Option<[u8; 32]>,
|
||||
key_id: Option<[u8; 8]>,
|
||||
cert: Option<Vec<u8>>,
|
||||
issuer: Option<String>,
|
||||
created: i64,
|
||||
pipelines: Vec<String>,
|
||||
repos: Vec<String>,
|
||||
pub(crate) struct Key {
|
||||
pub(crate) id: String,
|
||||
pub(crate) kind: KeyKind,
|
||||
pub(crate) role: Role,
|
||||
pub(crate) name: String,
|
||||
pub(crate) secret: Secret,
|
||||
pub(crate) public: Option<[u8; 32]>,
|
||||
pub(crate) key_id: Option<[u8; 8]>,
|
||||
pub(crate) cert: Option<Vec<u8>>,
|
||||
pub(crate) issuer: Option<String>,
|
||||
pub(crate) created: i64,
|
||||
pub(crate) pipelines: Vec<String>,
|
||||
pub(crate) repos: Vec<String>,
|
||||
}
|
||||
|
||||
impl fmt::Debug for Key {
|
||||
@@ -243,8 +266,8 @@ impl fmt::Debug for Key {
|
||||
/// The keys and the log, in the vault.
|
||||
#[derive(Debug, Default)]
|
||||
pub(crate) struct Store {
|
||||
keys: Vec<Key>,
|
||||
audit: Vec<AuditEntry>,
|
||||
pub(crate) keys: Vec<Key>,
|
||||
pub(crate) audit: Vec<AuditEntry>,
|
||||
standing: Vec<StandingRule>,
|
||||
}
|
||||
|
||||
@@ -321,6 +344,10 @@ impl Store {
|
||||
KeyKind::RootCa | KeyKind::CodeSigning | KeyKind::Android => {
|
||||
Secret::Rsa(RsaSecret::from_pkcs8_der(k.secret.expose().to_vec()).ok()?)
|
||||
}
|
||||
KeyKind::EcdsaP256 => {
|
||||
let scalar: [u8; 32] = k.secret.expose().try_into().ok()?;
|
||||
Secret::P256(custos_sign::P256Secret::from_bytes(scalar).ok()?)
|
||||
}
|
||||
};
|
||||
let public = match &k.public {
|
||||
Some(p) => Some(unb64(p)?.try_into().ok()?),
|
||||
@@ -380,6 +407,7 @@ impl Store {
|
||||
secret: SecretBytes::new(match &k.secret {
|
||||
Secret::Ed25519(s) => s.expose().to_vec(),
|
||||
Secret::Rsa(s) => s.expose().to_vec(),
|
||||
Secret::P256(s) => s.expose().to_vec(),
|
||||
}),
|
||||
public: k.public.map(|p| b64(&p)),
|
||||
key_id: k.key_id.map(|i| hex(&i)),
|
||||
@@ -393,13 +421,13 @@ impl Store {
|
||||
Some(StoreJson { keys, audit: self.audit.clone(), standing: self.standing.clone() })
|
||||
}
|
||||
|
||||
fn get(&self, id: &str) -> Option<&Key> {
|
||||
pub(crate) fn get(&self, id: &str) -> Option<&Key> {
|
||||
self.keys.iter().find(|k| k.id == id)
|
||||
}
|
||||
}
|
||||
|
||||
/// Unix seconds from the vault's milliseconds, as minisign and approvals count them.
|
||||
fn seconds(now_ms: i64) -> u64 {
|
||||
pub(crate) fn seconds(now_ms: i64) -> u64 {
|
||||
(now_ms.max(0) / 1000) as u64
|
||||
}
|
||||
|
||||
@@ -450,6 +478,8 @@ fn kind_word(kind: SignKind) -> &'static str {
|
||||
SignKind::Authenticode => "authenticode",
|
||||
SignKind::Approval => "approval",
|
||||
SignKind::Apk => "apk",
|
||||
SignKind::TauriUpdater => "tauri-updater",
|
||||
SignKind::Cosign => "cosign",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -665,6 +695,10 @@ impl Vault {
|
||||
},
|
||||
cert: k.cert.clone(),
|
||||
issuer: k.issuer.clone(),
|
||||
public_pem: match &k.secret {
|
||||
Secret::P256(s) => s.public_pem().ok(),
|
||||
_ => None,
|
||||
},
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -925,6 +959,10 @@ impl Vault {
|
||||
signature,
|
||||
reason,
|
||||
run,
|
||||
by: None,
|
||||
env: None,
|
||||
request: None,
|
||||
approvers: Vec::new(),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1156,6 +1194,7 @@ mod tests {
|
||||
.map(|k| match &k.secret {
|
||||
Secret::Ed25519(s) => s.expose().to_vec(),
|
||||
Secret::Rsa(s) => s.expose().to_vec(),
|
||||
Secret::P256(s) => s.expose().to_vec(),
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(secrets.len(), 9, "the release set with domi-approve, the test set, two Android keys");
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,441 @@
|
||||
//! Team vaults (docs/TEAM.md, core 0.18.0): opening, adding and removing members, the policy, signing every
|
||||
//! format, replays, target credentials.
|
||||
|
||||
use custos_team::external::{ExternalSigner, SignerCredential};
|
||||
use custos_team::policy::{EnvRule, KeyRole};
|
||||
use custos_team::request::{Artifact, Format, SignRequest, TargetRequest};
|
||||
use custos_team::target::{TargetKind, TargetRelease};
|
||||
use custos_team::{MemberKey, TeamError, verify_proof};
|
||||
use custos_vault::{Error, NewSigner, NewTarget, SecretString, Vault};
|
||||
|
||||
const NOW: i64 = 1_794_000_000_000;
|
||||
const NOW_S: u64 = 1_794_000_000;
|
||||
|
||||
struct Team {
|
||||
vault: Vault,
|
||||
a: MemberKey,
|
||||
b: MemberKey,
|
||||
}
|
||||
|
||||
/// Mark founds a team, makes its keys and adds Petra (comparing her join code).
|
||||
fn team() -> Team {
|
||||
let a = MemberKey::generate();
|
||||
let b = MemberKey::generate();
|
||||
let mut vault = Vault::create_team("Domi", &a, "Mark", &["mnovak".into()], NOW).unwrap();
|
||||
vault.team_create_keys(&a.id(), NOW).unwrap();
|
||||
let code = b.public().join_code();
|
||||
vault.team_add_member(&b.public(), "Petra", &["petra".into()], &a.id(), &code, NOW).unwrap();
|
||||
Team { vault, a, b }
|
||||
}
|
||||
|
||||
fn request(vault: &Vault, env: &str, author: &str, format: Format, fabrica: &custos_seal::Recipient) -> String {
|
||||
let (digest, image) = match format {
|
||||
Format::Minisign | Format::TauriUpdater => (custos_sign::blake2b512(b"the installer").to_vec(), ""),
|
||||
Format::Apk => (vec![5u8; 128], ""),
|
||||
Format::Cosign => (vec![6u8; 32], "registry.example/domi/arca"),
|
||||
Format::Authenticode => (vec![7u8; 32], ""),
|
||||
};
|
||||
SignRequest {
|
||||
team: vault.team_view().unwrap().id,
|
||||
id: custos_team::new_id(),
|
||||
project: "mnovak/Arca".into(),
|
||||
release: "0.7.0".into(),
|
||||
env: env.into(),
|
||||
author: author.into(),
|
||||
format,
|
||||
artifact: Artifact { name: "Arca_0.7.0_x64-setup.exe".into(), size: 13, sha256: custos_sign::sha256_hex(b"the installer") },
|
||||
artifact_digest: digest.to_vec(),
|
||||
image: image.into(),
|
||||
public: fabrica.public(),
|
||||
expires: NOW_S + 3600,
|
||||
}
|
||||
.canonical()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn members_open_the_team_vault_and_outsiders_do_not() {
|
||||
let t = team();
|
||||
let bytes = t.vault.to_bytes().unwrap();
|
||||
let (id, epoch, members) = Vault::team_peek(&bytes).unwrap();
|
||||
assert_eq!((id.as_str(), epoch, members.len()), (t.vault.team_view().unwrap().id.as_str(), 1, 2));
|
||||
for k in [&t.a, &t.b] {
|
||||
let v = Vault::open_team(&bytes, k).unwrap();
|
||||
assert!(v.is_team());
|
||||
assert_eq!(v.team_view().unwrap().members.len(), 2);
|
||||
assert_eq!(v.signing_keys().len(), 4);
|
||||
}
|
||||
assert!(matches!(Vault::open_team(&bytes, &MemberKey::generate()), Err(Error::NotAMember)));
|
||||
// A team vault is not a two-factor vault, and a personal vault is not a team vault.
|
||||
assert!(Vault::factor_kinds(&bytes).unwrap().is_empty());
|
||||
let mut personal = Vault::create(&SecretString::from("pw"), custos_vault::KdfParams { m_cost_kib: 8, t_cost: 1, p_cost: 1 }).unwrap();
|
||||
assert!(matches!(Vault::open_team(&personal.to_bytes().unwrap(), &t.a), Err(Error::NotATeam)));
|
||||
// A changed header byte (a member slot moved to another epoch) does not open.
|
||||
let mut moved = bytes.clone();
|
||||
moved[9 + 3 + 32] ^= 1;
|
||||
assert!(Vault::open_team(&moved, &t.a).is_err());
|
||||
// The member key lives in the member's own vault and survives a save.
|
||||
personal.member_key_create(NOW).unwrap();
|
||||
let again = Vault::open(&personal.to_bytes().unwrap(), &SecretString::from("pw")).unwrap();
|
||||
assert_eq!(again.member_key().unwrap().id(), personal.member_key().unwrap().id());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wrong_join_code_adds_nobody() {
|
||||
let mut t = team();
|
||||
let c = MemberKey::generate();
|
||||
let wrong = if c.public().join_code() == "111111" { "222222" } else { "111111" };
|
||||
let e = t.vault.team_add_member(&c.public(), "Eve", &[], &t.a.id(), wrong, NOW).unwrap_err();
|
||||
assert!(e.to_string().contains("match code"), "{e}");
|
||||
assert_eq!(t.vault.team_view().unwrap().members.len(), 2);
|
||||
// An outsider cannot add anyone either.
|
||||
let code = c.public().join_code();
|
||||
assert!(t.vault.team_add_member(&c.public(), "Eve", &[], &c.id(), &code, NOW).is_err());
|
||||
}
|
||||
|
||||
/// Mandatory: removing a member rotates the team key; the old member cannot unwrap anything created after.
|
||||
#[test]
|
||||
fn a_removed_member_cannot_open_anything_written_after() {
|
||||
let mut t = team();
|
||||
let before = t.vault.to_bytes().unwrap();
|
||||
assert!(Vault::open_team(&before, &t.b).is_ok());
|
||||
t.vault
|
||||
.team_add_target(
|
||||
NewTarget {
|
||||
kind: TargetKind::SshKey,
|
||||
name: "web-1".into(),
|
||||
project: "mnovak/Arca".into(),
|
||||
env: "production".into(),
|
||||
host: "web-1.example".into(),
|
||||
user: "deploy".into(),
|
||||
secret: SecretString::from("-----BEGIN OPENSSH PRIVATE KEY-----\nold\n"),
|
||||
},
|
||||
&t.a.id(),
|
||||
NOW,
|
||||
)
|
||||
.unwrap();
|
||||
let removal = t.vault.team_remove_member(&t.b.id(), &t.a.id(), NOW + 1).unwrap();
|
||||
assert_eq!(removal.epoch, 2);
|
||||
assert_eq!(removal.rotate, vec!["target web-1".to_string()]);
|
||||
// Something created after the removal.
|
||||
t.vault
|
||||
.team_add_target(
|
||||
NewTarget {
|
||||
kind: TargetKind::Registry,
|
||||
name: "registry".into(),
|
||||
project: "mnovak/Arca".into(),
|
||||
env: "production".into(),
|
||||
host: String::new(),
|
||||
user: String::new(),
|
||||
secret: SecretString::from("new-registry-token-after-removal"),
|
||||
},
|
||||
&t.a.id(),
|
||||
NOW + 2,
|
||||
)
|
||||
.unwrap();
|
||||
let after = t.vault.to_bytes().unwrap();
|
||||
// B has no slot, and B's old slot (from the earlier file) does not open the new body.
|
||||
assert!(matches!(Vault::open_team(&after, &t.b), Err(Error::NotAMember)));
|
||||
let (_, epoch, members) = Vault::team_peek(&after).unwrap();
|
||||
assert_eq!((epoch, members), (2, vec![t.a.id()]));
|
||||
let mut spliced = Vec::new();
|
||||
let (hb, _) = header_len(&before);
|
||||
let (ha, _) = header_len(&after);
|
||||
spliced.extend_from_slice(&before[..hb]);
|
||||
spliced.extend_from_slice(&after[ha..]);
|
||||
assert!(Vault::open_team(&spliced, &t.b).is_err(), "the old key does not open the new body");
|
||||
// The new token is in no byte of the file B can read.
|
||||
assert!(!contains(&after, b"new-registry-token"));
|
||||
// A still opens it, at epoch 2, and B is listed as removed.
|
||||
let v = Vault::open_team(&after, &t.a).unwrap();
|
||||
let view = v.team_view().unwrap();
|
||||
assert_eq!((view.epoch, view.members.len(), view.removed[0].name.as_str()), (2, 1, "Petra"));
|
||||
// The last member cannot be removed.
|
||||
let mut v = v;
|
||||
assert!(v.team_remove_member(&t.a.id(), &t.a.id(), NOW).is_err());
|
||||
}
|
||||
|
||||
fn header_len(bytes: &[u8]) -> (usize, ()) {
|
||||
let count = bytes[8] as usize;
|
||||
let mut at = 9;
|
||||
for _ in 0..count {
|
||||
let len = u16::from_le_bytes([bytes[at + 1], bytes[at + 2]]) as usize;
|
||||
at += 3 + len;
|
||||
}
|
||||
(at + 24, ())
|
||||
}
|
||||
|
||||
fn contains(hay: &[u8], needle: &[u8]) -> bool {
|
||||
hay.windows(needle.len()).any(|w| w == needle)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_member_refuses_an_older_copy_or_another_identity() {
|
||||
let mut t = team();
|
||||
let mut own = Vault::create(&SecretString::from("pw"), custos_vault::KdfParams { m_cost_kib: 8, t_cost: 1, p_cost: 1 }).unwrap();
|
||||
// Mark's own vault holds his member key; the team was made with the same key.
|
||||
let c = MemberKey::generate();
|
||||
let code = c.public().join_code();
|
||||
t.vault.team_add_member(&c.public(), "Third", &[], &t.a.id(), &code, NOW).unwrap();
|
||||
own.member_key_create(NOW).unwrap();
|
||||
let old = Vault::open_team(&t.vault.to_bytes().unwrap(), &t.a).unwrap();
|
||||
t.vault.team_remove_member(&c.id(), &t.a.id(), NOW).unwrap();
|
||||
let new = Vault::open_team(&t.vault.to_bytes().unwrap(), &t.a).unwrap();
|
||||
own.member_note_team(&new).unwrap();
|
||||
assert!(matches!(own.member_note_team(&old), Err(Error::TeamRollback)));
|
||||
let impostor = Vault::create_team("Domi", &t.a, "Mark", &[], NOW).unwrap();
|
||||
own.member_note_team(&impostor).unwrap(); // another id: a team of its own
|
||||
assert_eq!(own.member_teams().len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_policy_is_set_per_environment_signed_and_kept() {
|
||||
let mut t = team();
|
||||
let p = t
|
||||
.vault
|
||||
.team_set_rule(EnvRule { env: "staging".into(), approvals: 1, others: true, approvers: vec![t.b.id()] }, &t.a.id(), NOW)
|
||||
.unwrap();
|
||||
assert_eq!(p.rev, 2);
|
||||
assert!(t.vault.team_set_rule(EnvRule { env: "staging".into(), approvals: 1, others: true, approvers: vec!["ab".repeat(16)] }, &t.a.id(), NOW).is_err());
|
||||
let v = Vault::open_team(&t.vault.to_bytes().unwrap(), &t.b).unwrap();
|
||||
let (text, sig) = v.team_policy_signed().unwrap();
|
||||
assert!(custos_team::member::verify_policy_sig(&v.team_identity().unwrap(), &text, &sig));
|
||||
assert_eq!(v.team_policy().unwrap().rule("staging").unwrap().approvers, vec![t.b.id()]);
|
||||
assert!(v.team_audit().unwrap().iter().any(|e| e.detail.as_deref() == Some("staging: 1 approval(s), not the author")));
|
||||
}
|
||||
|
||||
/// Mandatory: a signing request with a wrong or replayed match code is refused.
|
||||
#[test]
|
||||
fn wrong_and_replayed_match_codes_are_refused() {
|
||||
let mut t = team();
|
||||
let fabrica = custos_seal::Recipient::generate();
|
||||
let text = request(&t.vault, "production", "mnovak", Format::Minisign, &fabrica);
|
||||
let code = fabrica.match_code();
|
||||
let wrong = if code == "000000" { "000001" } else { "000000" };
|
||||
// Petra's card showed another code: nothing is signed, nothing recorded as seen.
|
||||
assert_eq!(t.vault.team_sign(&text, &[], &t.b, Some(wrong), None, NOW).unwrap_err(), TeamError::WrongMatch);
|
||||
assert_eq!(t.vault.team_approve(&text, &t.b, wrong, NOW).unwrap_err(), TeamError::WrongMatch);
|
||||
// The author may not approve production in a team of two.
|
||||
assert!(matches!(t.vault.team_sign(&text, &[], &t.a, Some(&code), None, NOW), Err(TeamError::NotEligible(_))));
|
||||
// Petra with the right code signs.
|
||||
let reply = t.vault.team_sign(&text, &[], &t.b, Some(&code), None, NOW).unwrap();
|
||||
// The same request again (a replay): refused, by this vault, whoever asks.
|
||||
assert_eq!(t.vault.team_sign(&text, &[], &t.b, Some(&code), None, NOW).unwrap_err(), TeamError::Replayed);
|
||||
assert_eq!(t.vault.team_check_request(&text, NOW).unwrap_err(), TeamError::Replayed);
|
||||
// ... also after a save and reopen, and in Mark's copy once he has the saved file.
|
||||
let reopened = Vault::open_team(&t.vault.to_bytes().unwrap(), &t.a).unwrap();
|
||||
assert_eq!(reopened.team_check_request(&text, NOW).unwrap_err(), TeamError::Replayed);
|
||||
// Petra's approval statement from this request does not count for another one.
|
||||
let other = request(&t.vault, "production", "mnovak", Format::Minisign, &custos_seal::Recipient::generate());
|
||||
let statements: Vec<_> = custos_team::proof::ProofBody::parse(&reply.proof.text).unwrap().approvals;
|
||||
let req = SignRequest::parse(&other).unwrap();
|
||||
let eval = t.vault.team_evaluate(&req, &statements).unwrap();
|
||||
assert!(eval.counted.is_empty());
|
||||
// An expired request.
|
||||
let late = request(&t.vault, "staging", "mnovak", Format::Minisign, &fabrica);
|
||||
assert_eq!(t.vault.team_sign(&late, &[], &t.a, Some(&code), None, NOW + 3_601_000).unwrap_err(), TeamError::Expired);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_approvals_collect_statements_and_the_last_approver_signs() {
|
||||
let mut t = team();
|
||||
let c = MemberKey::generate();
|
||||
let code = c.public().join_code();
|
||||
t.vault.team_add_member(&c.public(), "Jan", &[], &t.a.id(), &code, NOW).unwrap();
|
||||
t.vault.team_set_rule(EnvRule { env: "production".into(), approvals: 2, others: true, approvers: vec![] }, &t.a.id(), NOW).unwrap();
|
||||
let fabrica = custos_seal::Recipient::generate();
|
||||
let text = request(&t.vault, "production", "mnovak", Format::Minisign, &fabrica);
|
||||
let code = fabrica.match_code();
|
||||
// Petra alone is not enough: she approves (a statement), she does not sign.
|
||||
assert_eq!(t.vault.team_sign(&text, &[], &t.b, Some(&code), None, NOW).unwrap_err(), TeamError::NeedMore(1));
|
||||
let petra = t.vault.team_approve(&text, &t.b, &code, NOW).unwrap();
|
||||
// Mark's statement (the author) does not count; Jan's does, and Jan signs.
|
||||
let reply = t.vault.team_sign(&text, &[petra.clone()], &c, Some(&code), None, NOW).unwrap();
|
||||
let v = verify_proof(&reply.proof, &t.vault.team_identity().unwrap(), &text, reply.envelope()).unwrap();
|
||||
assert_eq!(v.approvers.len(), 2);
|
||||
assert_eq!(v.signer, c.id());
|
||||
let audit = t.vault.signing_audit().last().unwrap().clone();
|
||||
assert_eq!(audit.by.as_deref(), Some(c.id().as_str()));
|
||||
assert_eq!(audit.approvers.len(), 2);
|
||||
assert_eq!(audit.env.as_deref(), Some("production"));
|
||||
}
|
||||
|
||||
struct FakeHsm(custos_sign::RsaSecret);
|
||||
|
||||
impl ExternalSigner for FakeHsm {
|
||||
fn sign_digest(&self, signer: &SignerCredential<'_>, digest: &[u8; 32]) -> Result<Vec<u8>, String> {
|
||||
if signer.secret != "hsm-pin" {
|
||||
return Err("wrong credential".into());
|
||||
}
|
||||
custos_sign::authenticode(&self.0, digest).map_err(|e| e.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
/// Every format signs and the proof checks; the signatures verify (minisign-verify is minisign's and Tauri's own
|
||||
/// verifier; cosign with p256 here and openssl in custos-sign's tests).
|
||||
#[test]
|
||||
fn every_format_signs_with_the_right_key_and_verifies() {
|
||||
let mut t = team();
|
||||
let identity = t.vault.team_identity().unwrap();
|
||||
t.vault
|
||||
.team_create_android(
|
||||
&custos_vault::signing::AndroidKey {
|
||||
id: "arca-android".into(),
|
||||
name: "Arca Android".into(),
|
||||
cn: "Arca".into(),
|
||||
o: "Domi".into(),
|
||||
c: "CZ".into(),
|
||||
role: custos_vault::signing::Role::Release,
|
||||
pipelines: vec!["*".into()],
|
||||
repos: vec!["mnovak/Arca".into()],
|
||||
},
|
||||
&t.a.id(),
|
||||
NOW,
|
||||
)
|
||||
.unwrap();
|
||||
let hsm = custos_sign::new_root("Fake HSM", 1).unwrap();
|
||||
t.vault
|
||||
.team_add_signer(
|
||||
NewSigner {
|
||||
name: "Fake cloud signer".into(),
|
||||
adapter: "command".into(),
|
||||
endpoint: "https://signer.example".into(),
|
||||
account: "domi".into(),
|
||||
secret: SecretString::from("hsm-pin"),
|
||||
certificate: hsm.cert_der.clone(),
|
||||
},
|
||||
&t.a.id(),
|
||||
NOW,
|
||||
)
|
||||
.unwrap();
|
||||
let ext = FakeHsm(hsm.secret);
|
||||
for format in [Format::Minisign, Format::TauriUpdater, Format::Cosign, Format::Apk, Format::Authenticode] {
|
||||
let fabrica = custos_seal::Recipient::generate();
|
||||
let text = request(&t.vault, "production", "mnovak", format, &fabrica);
|
||||
let reply = t.vault.team_sign(&text, &[], &t.b, Some(&fabrica.match_code()), Some(&ext), NOW).unwrap();
|
||||
let v = verify_proof(&reply.proof, &identity, &text, reply.envelope()).unwrap();
|
||||
assert_eq!(v.role, KeyRole::Release, "{format:?}");
|
||||
assert_eq!(reply.signer.name, "Petra");
|
||||
match format {
|
||||
Format::Minisign | Format::TauriUpdater => {
|
||||
assert_eq!(reply.key.id, "team-release");
|
||||
let minisig = if format == Format::TauriUpdater {
|
||||
custos_sign::tauri_updater_open(&reply.signature).unwrap()
|
||||
} else {
|
||||
reply.signature.clone()
|
||||
};
|
||||
let pk = minisign_verify::PublicKey::decode(&reply.key.public).unwrap();
|
||||
pk.verify(b"the installer", &minisign_verify::Signature::decode(&minisig).unwrap(), true).unwrap();
|
||||
}
|
||||
Format::Cosign => {
|
||||
assert_eq!(reply.key.id, "team-cosign");
|
||||
let payload = reply.payload.as_deref().unwrap();
|
||||
assert!(payload.contains("\"docker-reference\":\"registry.example/domi/arca\""));
|
||||
let der = data_encoding::BASE64.decode(reply.signature.as_bytes()).unwrap();
|
||||
assert!(custos_sign::cosign_verify(&reply.key.public, payload.as_bytes(), &der));
|
||||
}
|
||||
Format::Apk => {
|
||||
assert_eq!(reply.key.id, "arca-android");
|
||||
let sig = data_encoding::BASE64.decode(reply.signature.as_bytes()).unwrap();
|
||||
assert_eq!(sig.len(), 2 * 512);
|
||||
assert!(reply.key.public.starts_with("-----BEGIN CERTIFICATE-----"));
|
||||
}
|
||||
Format::Authenticode => {
|
||||
assert!(reply.key.id.starts_with("signer:"));
|
||||
assert_eq!(data_encoding::BASE64.decode(reply.signature.as_bytes()).unwrap().len(), 384);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Preview: 0 approvals, the test key, no code needed; a release key never signs it.
|
||||
let fabrica = custos_seal::Recipient::generate();
|
||||
let text = request(&t.vault, "preview", "mnovak", Format::Minisign, &fabrica);
|
||||
let reply = t.vault.team_sign(&text, &[], &t.a, None, None, NOW).unwrap();
|
||||
assert_eq!(reply.key.id, "team-preview");
|
||||
let v = verify_proof(&reply.proof, &identity, &text, reply.envelope()).unwrap();
|
||||
assert_eq!(v.role, KeyRole::Test);
|
||||
// Authenticode is never signed without an approval, and not without the adapter.
|
||||
let text = request(&t.vault, "preview", "mnovak", Format::Authenticode, &fabrica);
|
||||
assert!(t.vault.team_sign(&text, &[], &t.a, None, Some(&ext), NOW).is_err());
|
||||
let text = request(&t.vault, "production", "mnovak", Format::Authenticode, &custos_seal::Recipient::generate());
|
||||
let code = SignRequest::parse(&text).unwrap().match_code();
|
||||
assert!(t.vault.team_sign(&text, &[], &t.b, Some(&code), None, NOW).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_target_credential_is_released_once_for_a_signed_deployment_of_its_project_and_environment() {
|
||||
let mut t = team();
|
||||
let target = t
|
||||
.vault
|
||||
.team_add_target(
|
||||
NewTarget {
|
||||
kind: TargetKind::Kubeconfig,
|
||||
name: "prod cluster".into(),
|
||||
project: "mnovak/Arca".into(),
|
||||
env: "production".into(),
|
||||
host: "k8s.example".into(),
|
||||
user: "fabrica".into(),
|
||||
secret: SecretString::from("apiVersion: v1\nkind: Config\n"),
|
||||
},
|
||||
&t.a.id(),
|
||||
NOW,
|
||||
)
|
||||
.unwrap();
|
||||
assert!(!format!("{:?}", t.vault.team_targets().unwrap()).contains("apiVersion"));
|
||||
let team_id = t.vault.team_view().unwrap().id;
|
||||
let fabrica = custos_seal::Recipient::generate();
|
||||
let ask = |deployment: &str| TargetRequest {
|
||||
team: team_id.clone(),
|
||||
id: custos_team::new_id(),
|
||||
target: target.clone(),
|
||||
deployment: deployment.into(),
|
||||
public: fabrica.public(),
|
||||
expires: NOW_S + 600,
|
||||
}
|
||||
.canonical();
|
||||
// No signed deployment yet.
|
||||
let unsigned = "ab".repeat(32);
|
||||
assert!(t.vault.team_target_release(&ask(&unsigned), &t.b.id(), NOW).is_err());
|
||||
// A staging deployment is not a production one.
|
||||
let staging = request(&t.vault, "staging", "mnovak", Format::Minisign, &fabrica);
|
||||
let r = t.vault.team_sign(&staging, &[], &t.a, Some(&fabrica.match_code()), None, NOW).unwrap();
|
||||
assert!(t.vault.team_target_release(&ask(&r.request), &t.b.id(), NOW).is_err());
|
||||
let prod = request(&t.vault, "production", "mnovak", Format::Minisign, &fabrica);
|
||||
let r = t.vault.team_sign(&prod, &[], &t.b, Some(&fabrica.match_code()), None, NOW).unwrap();
|
||||
let (json, req) = t.vault.team_target_release(&ask(&r.request), &t.b.id(), NOW).unwrap();
|
||||
let released: TargetRelease = serde_json::from_str(&json).unwrap();
|
||||
assert_eq!((released.secret.as_str(), released.env.as_str()), ("apiVersion: v1\nkind: Config\n", "production"));
|
||||
assert!(!format!("{released:?}").contains("apiVersion"));
|
||||
assert_eq!(req.reply_context(), format!("team-target:{}", req.id).into_bytes());
|
||||
// Once per deployment.
|
||||
assert!(t.vault.team_target_release(&ask(&r.request), &t.b.id(), NOW).unwrap_err().to_string().contains("replay"));
|
||||
// Too late: a deployment signed more than 25 hours ago.
|
||||
assert!(t.vault.team_target_release(&ask(&r.request), &t.b.id(), NOW + 26 * 3_600_000).is_err());
|
||||
assert!(t.vault.team_audit().unwrap().iter().any(|e| e.action == custos_vault::TeamAction::TargetReleased));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_secret_prints_or_reaches_a_view() {
|
||||
let mut t = team();
|
||||
t.vault
|
||||
.team_add_signer(
|
||||
NewSigner {
|
||||
name: "HSM".into(),
|
||||
adapter: "command".into(),
|
||||
endpoint: String::new(),
|
||||
account: String::new(),
|
||||
secret: SecretString::from("very-secret-pin-123"),
|
||||
certificate: vec![],
|
||||
},
|
||||
&t.a.id(),
|
||||
NOW,
|
||||
)
|
||||
.unwrap();
|
||||
let shown = format!(
|
||||
"{:?} {:?} {:?} {:?}",
|
||||
t.vault,
|
||||
t.vault.team_view(),
|
||||
t.vault.team_signers().unwrap(),
|
||||
serde_json::to_string(&t.vault.team_view()).unwrap()
|
||||
);
|
||||
assert!(!shown.contains("very-secret-pin-123"));
|
||||
assert!(!contains(&t.vault.to_bytes().unwrap(), b"very-secret-pin-123"));
|
||||
}
|
||||
Reference in New Issue
Block a user