[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:
@@ -0,0 +1,54 @@
|
||||
//! The canonical JSON every signed text here uses (as deploy approvals, SIGNING.md): fixed key order, no spaces,
|
||||
//! `"` and `\` escaped and nothing else, no newline. Callers only write strings that passed [`text_ok`].
|
||||
|
||||
/// Appends `s` as a JSON string with minimal escaping.
|
||||
pub 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('"');
|
||||
}
|
||||
|
||||
/// Appends `["a","b"]`.
|
||||
pub fn strings(out: &mut String, list: &[String]) {
|
||||
out.push('[');
|
||||
for (i, s) in list.iter().enumerate() {
|
||||
if i > 0 {
|
||||
out.push(',');
|
||||
}
|
||||
string(out, s);
|
||||
}
|
||||
out.push(']');
|
||||
}
|
||||
|
||||
/// Characters a shown text may not hold: control characters, and the invisible ones that change how a line looks
|
||||
/// on a card (bidi overrides and isolates, zero-width characters, line separators, soft hyphen).
|
||||
pub 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}')
|
||||
}
|
||||
|
||||
/// 1..=`max` characters, none of them [`unprintable`].
|
||||
pub fn text_ok(s: &str, max: usize) -> bool {
|
||||
(1..=max).contains(&s.chars().count()) && !s.chars().any(unprintable)
|
||||
}
|
||||
|
||||
/// `min..=max` bytes, every one ASCII alphanumeric or in `extra`.
|
||||
pub fn ascii_ok(s: &str, min: usize, max: usize, extra: &[u8]) -> bool {
|
||||
(min..=max).contains(&s.len()) && s.bytes().all(|c| c.is_ascii_alphanumeric() || extra.contains(&c))
|
||||
}
|
||||
|
||||
/// An environment name: `[a-z][a-z0-9-]{0,31}`.
|
||||
pub fn env_ok(s: &str) -> bool {
|
||||
let b = s.as_bytes();
|
||||
!b.is_empty()
|
||||
&& b.len() <= 32
|
||||
&& b[0].is_ascii_lowercase()
|
||||
&& b.iter().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || *c == b'-')
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
//! The one interface an external signer is reached through (docs/TEAM.md, Authenticode). A hardware token or a
|
||||
//! cloud signing service holds the private key; Custos approves, then hands the adapter the digest and the
|
||||
//! credential that lets it ask. Adapters are the app's (I/O); this crate only names the shape.
|
||||
|
||||
use std::fmt;
|
||||
|
||||
/// The credential an adapter uses, borrowed from the team vault for one call. Prints `[redacted]` for `secret`.
|
||||
pub struct SignerCredential<'a> {
|
||||
pub id: &'a str,
|
||||
pub name: &'a str,
|
||||
/// Which adapter: `command` in this phase.
|
||||
pub adapter: &'a str,
|
||||
pub endpoint: &'a str,
|
||||
pub account: &'a str,
|
||||
pub secret: &'a str,
|
||||
}
|
||||
|
||||
impl fmt::Debug for SignerCredential<'_> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("SignerCredential")
|
||||
.field("id", &self.id)
|
||||
.field("adapter", &self.adapter)
|
||||
.field("endpoint", &self.endpoint)
|
||||
.field("secret", &"[redacted]")
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
/// Signs a 32-byte SHA-256 digest (signtool's `.dig`) with a key Custos never holds: returns the raw signature
|
||||
/// (RSA PKCS#1 v1.5 over the SHA-256 DigestInfo, as `signtool sign /di` wants it). An error names what failed,
|
||||
/// never the credential.
|
||||
pub trait ExternalSigner {
|
||||
fn sign_digest(&self, signer: &SignerCredential<'_>, digest: &[u8; 32]) -> Result<Vec<u8>, String>;
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
//! Custos Domi · teams (docs/TEAM.md, core 0.18.0): the pure parts of team vaults and team signing.
|
||||
//!
|
||||
//! - [`member`]: a person's member key (X25519 to receive the team key, Ed25519 to sign approvals), the member id,
|
||||
//! the join code, and sealing the team key to a member;
|
||||
//! - [`policy`]: one rule per environment, its canonical text, and [`policy::evaluate`];
|
||||
//! - [`request`]: the canonical `sign.request` and `target.request`, their hash and match code;
|
||||
//! - [`statement`]: a member's signed approval of one request;
|
||||
//! - [`proof`]: the team identity's policy proof, and checking it;
|
||||
//! - [`reply`]: what goes back to Fabrica, sealed; [`target`]: a released target credential;
|
||||
//! - [`external`]: the interface an external signer (a hardware token, a cloud signing service) is reached through.
|
||||
//!
|
||||
//! No I/O, no clock: every check takes `now` from the caller. Secrets print as `[redacted]`.
|
||||
|
||||
pub mod canon;
|
||||
pub mod external;
|
||||
pub mod member;
|
||||
pub mod policy;
|
||||
pub mod proof;
|
||||
pub mod reply;
|
||||
pub mod request;
|
||||
pub mod statement;
|
||||
pub mod target;
|
||||
|
||||
pub use member::{MemberKey, MemberPublic, TeamIdentity};
|
||||
pub use policy::{EnvRule, Evaluation, KeyRole, Policy, RosterMember, Verdict, evaluate};
|
||||
pub use proof::{Proof, Verified, verify_proof};
|
||||
pub use request::{Format, SignRequest, TargetRequest};
|
||||
pub use statement::Statement;
|
||||
|
||||
/// How far ahead a request may expire: 25 hours, as deploy approvals (SIGNING.md).
|
||||
pub const MAX_AHEAD_SECS: u64 = 25 * 3600;
|
||||
/// How long a signed request's hash is remembered against replay: longer than any request lives.
|
||||
pub const SEEN_SECS: u64 = 48 * 3600;
|
||||
/// The most members a team has (member slots in one file).
|
||||
pub const MAX_MEMBERS: usize = 32;
|
||||
|
||||
/// Why something is refused. None of them carries a key, a credential or a signature.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
|
||||
pub enum TeamError {
|
||||
#[error("not in canonical form: {0}")]
|
||||
NotCanonical(&'static str),
|
||||
#[error("{0}")]
|
||||
Invalid(&'static str),
|
||||
#[error("the request has expired")]
|
||||
Expired,
|
||||
#[error("the match code is not this request's: someone else's request may be waiting, refuse it")]
|
||||
WrongMatch,
|
||||
#[error("this request was already answered: a replay is refused")]
|
||||
Replayed,
|
||||
#[error("the request is for another team")]
|
||||
WrongTeam,
|
||||
#[error("not a member of this team")]
|
||||
NotAMember,
|
||||
#[error("a signature does not verify")]
|
||||
BadSignature,
|
||||
#[error("the policy has no rule for this environment")]
|
||||
UnknownEnv,
|
||||
#[error("the policy cannot be met: {0}")]
|
||||
Unsatisfiable(&'static str),
|
||||
#[error("the policy needs {0} more approval(s)")]
|
||||
NeedMore(u8),
|
||||
#[error("this member may not approve this request: {0}")]
|
||||
NotEligible(&'static str),
|
||||
#[error("the key cannot be read")]
|
||||
BadKey,
|
||||
}
|
||||
|
||||
pub(crate) fn hex(b: &[u8]) -> String {
|
||||
data_encoding::HEXLOWER.encode(b)
|
||||
}
|
||||
|
||||
pub(crate) fn unhex<const N: usize>(s: &str) -> Option<[u8; N]> {
|
||||
let v = data_encoding::HEXLOWER.decode(s.as_bytes()).ok()?;
|
||||
v.try_into().ok()
|
||||
}
|
||||
|
||||
pub(crate) fn b64(b: &[u8]) -> String {
|
||||
data_encoding::BASE64.encode(b)
|
||||
}
|
||||
|
||||
pub(crate) fn unb64(s: &str) -> Option<Vec<u8>> {
|
||||
data_encoding::BASE64.decode(s.as_bytes()).ok()
|
||||
}
|
||||
|
||||
pub(crate) fn sha256(b: &[u8]) -> [u8; 32] {
|
||||
use sha2::Digest;
|
||||
sha2::Sha256::digest(b).into()
|
||||
}
|
||||
|
||||
/// 32 lower-case hex digits: a team, member or request id.
|
||||
pub fn id_ok(s: &str) -> bool {
|
||||
s.len() == 32 && s.bytes().all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c))
|
||||
}
|
||||
|
||||
/// A random 16-byte id, hex.
|
||||
pub fn new_id() -> String {
|
||||
let mut b = [0u8; 16];
|
||||
rand::Rng::fill_bytes(&mut rand::rand_core::UnwrapErr(rand::rngs::SysRng), &mut b);
|
||||
hex(&b)
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
//! A person's member key, the team identity, and sealing the team key to a member (docs/TEAM.md, "The member key",
|
||||
//! "The team vault file").
|
||||
|
||||
use std::fmt;
|
||||
|
||||
use custos_seal::Recipient;
|
||||
use ed25519_dalek::{Signature, Signer, SigningKey, VerifyingKey};
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
use crate::{TeamError, hex, sha256};
|
||||
|
||||
/// The size of a sealed team key: custos-seal's box around 32 bytes.
|
||||
pub const SEALED_KEY_LEN: usize = 4 + 32 + 24 + 32 + 16;
|
||||
|
||||
/// The public half of a member key, as the roster and the service keep it.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct MemberPublic {
|
||||
pub ed25519: [u8; 32],
|
||||
pub x25519: [u8; 32],
|
||||
}
|
||||
|
||||
impl MemberPublic {
|
||||
/// The member id: the first 16 bytes of `SHA-256("custos member v1" ‖ ed25519 ‖ x25519)`, 32 hex.
|
||||
pub fn id(&self) -> String {
|
||||
hex(&self.id_bytes())
|
||||
}
|
||||
|
||||
pub fn id_bytes(&self) -> [u8; 16] {
|
||||
let mut m = Vec::with_capacity(16 + 64);
|
||||
m.extend_from_slice(b"custos member v1");
|
||||
m.extend_from_slice(&self.ed25519);
|
||||
m.extend_from_slice(&self.x25519);
|
||||
sha256(&m)[..16].try_into().expect("16 bytes")
|
||||
}
|
||||
|
||||
/// The code a joining member's screen shows and the approving member compares: `match_code(x25519)`.
|
||||
pub fn join_code(&self) -> String {
|
||||
custos_seal::match_code(&self.x25519)
|
||||
}
|
||||
|
||||
/// Both keys must be usable: an Ed25519 point and a contributory X25519 key.
|
||||
pub fn check(&self) -> Result<(), TeamError> {
|
||||
VerifyingKey::from_bytes(&self.ed25519).map_err(|_| TeamError::BadKey)?;
|
||||
custos_seal::seal(&self.x25519, b"check", b"").map_err(|_| TeamError::BadKey)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Checks an Ed25519 signature by this member over `msg`.
|
||||
pub fn verify(&self, msg: &[u8], sig: &[u8; 64]) -> bool {
|
||||
verify(&self.ed25519, msg, sig)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn verify(public: &[u8; 32], msg: &[u8], sig: &[u8; 64]) -> bool {
|
||||
let Ok(key) = VerifyingKey::from_bytes(public) else {
|
||||
return false;
|
||||
};
|
||||
key.verify_strict(msg, &Signature::from_bytes(sig)).is_ok()
|
||||
}
|
||||
|
||||
/// The context a team key is sealed under for one member slot.
|
||||
pub fn key_context(team: &str, epoch: u32, member: &str) -> Vec<u8> {
|
||||
format!("custos team key v1:{team}:{epoch}:{member}").into_bytes()
|
||||
}
|
||||
|
||||
/// Seals the 32-byte team key to a member for one team and epoch: the member slot's box ([`SEALED_KEY_LEN`] bytes).
|
||||
pub fn seal_team_key(team_key: &[u8; 32], to: &MemberPublic, team: &str, epoch: u32) -> Result<Vec<u8>, TeamError> {
|
||||
custos_seal::seal(&to.x25519, &key_context(team, epoch, &to.id()), team_key).map_err(|_| TeamError::BadKey)
|
||||
}
|
||||
|
||||
/// A person's member key. Lives in their own vault; wiped on drop; prints `[redacted]`.
|
||||
pub struct MemberKey {
|
||||
x: Recipient,
|
||||
ed: SigningKey,
|
||||
}
|
||||
|
||||
impl MemberKey {
|
||||
/// A new member key from the OS CSPRNG.
|
||||
pub fn generate() -> MemberKey {
|
||||
let ed = custos_seal::random_bytes();
|
||||
MemberKey { x: Recipient::generate(), ed: SigningKey::from_bytes(&ed) }
|
||||
}
|
||||
|
||||
/// The key as the member's vault keeps it.
|
||||
pub fn from_secrets(x25519: Zeroizing<[u8; 32]>, ed25519: Zeroizing<[u8; 32]>) -> Result<MemberKey, TeamError> {
|
||||
let x = Recipient::from_secret(x25519).map_err(|_| TeamError::BadKey)?;
|
||||
Ok(MemberKey { x, ed: SigningKey::from_bytes(&ed25519) })
|
||||
}
|
||||
|
||||
/// The X25519 secret, for the member's own vault only.
|
||||
pub fn x25519_secret(&self) -> Zeroizing<[u8; 32]> {
|
||||
self.x.secret_bytes()
|
||||
}
|
||||
|
||||
/// The Ed25519 seed, for the member's own vault only.
|
||||
pub fn ed25519_secret(&self) -> Zeroizing<[u8; 32]> {
|
||||
Zeroizing::new(self.ed.to_bytes())
|
||||
}
|
||||
|
||||
pub fn public(&self) -> MemberPublic {
|
||||
MemberPublic { ed25519: self.ed.verifying_key().to_bytes(), x25519: self.x.public() }
|
||||
}
|
||||
|
||||
pub fn id(&self) -> String {
|
||||
self.public().id()
|
||||
}
|
||||
|
||||
/// Opens this member's slot of a team vault: the team key.
|
||||
pub fn open_team_key(&self, sealed: &[u8], team: &str, epoch: u32) -> Result<Zeroizing<[u8; 32]>, TeamError> {
|
||||
let k = self.x.open(sealed, &key_context(team, epoch, &self.id())).map_err(|_| TeamError::NotAMember)?;
|
||||
let k: [u8; 32] = k.as_slice().try_into().map_err(|_| TeamError::NotAMember)?;
|
||||
Ok(Zeroizing::new(k))
|
||||
}
|
||||
|
||||
/// Signs `msg` with the member's Ed25519 key (approval statements only; the domain is the caller's prefix).
|
||||
pub(crate) fn sign(&self, msg: &[u8]) -> [u8; 64] {
|
||||
self.ed.sign(msg).to_bytes()
|
||||
}
|
||||
|
||||
/// Opens a box sealed to this member's X25519 key (for a joiner: nothing else is ever sealed to it).
|
||||
pub fn recipient(&self) -> &Recipient {
|
||||
&self.x
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for MemberKey {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str("[redacted]")
|
||||
}
|
||||
}
|
||||
|
||||
/// The team identity: an Ed25519 key in the team body that signs the policy and the proofs, and never rotates.
|
||||
pub struct TeamIdentity(SigningKey);
|
||||
|
||||
/// Domain prefixes, so a signature of one kind never passes for another.
|
||||
pub const POLICY_DOMAIN: &[u8] = b"custos team policy v1\0";
|
||||
pub const PROOF_DOMAIN: &[u8] = b"custos team proof v1\0";
|
||||
|
||||
impl TeamIdentity {
|
||||
pub fn generate() -> TeamIdentity {
|
||||
TeamIdentity(SigningKey::from_bytes(&custos_seal::random_bytes()))
|
||||
}
|
||||
|
||||
pub fn from_secret(secret: &[u8; 32]) -> TeamIdentity {
|
||||
TeamIdentity(SigningKey::from_bytes(secret))
|
||||
}
|
||||
|
||||
pub fn secret(&self) -> Zeroizing<[u8; 32]> {
|
||||
Zeroizing::new(self.0.to_bytes())
|
||||
}
|
||||
|
||||
pub fn public(&self) -> [u8; 32] {
|
||||
self.0.verifying_key().to_bytes()
|
||||
}
|
||||
|
||||
pub fn sign_policy(&self, text: &str) -> [u8; 64] {
|
||||
self.0.sign(&[POLICY_DOMAIN, text.as_bytes()].concat()).to_bytes()
|
||||
}
|
||||
|
||||
pub fn sign_proof(&self, text: &str) -> [u8; 64] {
|
||||
self.0.sign(&[PROOF_DOMAIN, text.as_bytes()].concat()).to_bytes()
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for TeamIdentity {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str("[redacted]")
|
||||
}
|
||||
}
|
||||
|
||||
/// Checks the team identity's signature on a policy text.
|
||||
pub fn verify_policy_sig(identity: &[u8; 32], text: &str, sig: &[u8; 64]) -> bool {
|
||||
verify(identity, &[POLICY_DOMAIN, text.as_bytes()].concat(), sig)
|
||||
}
|
||||
|
||||
/// Checks the team identity's signature on a proof text.
|
||||
pub fn verify_proof_sig(identity: &[u8; 32], text: &str, sig: &[u8; 64]) -> bool {
|
||||
verify(identity, &[PROOF_DOMAIN, text.as_bytes()].concat(), sig)
|
||||
}
|
||||
@@ -0,0 +1,277 @@
|
||||
//! The approval policy: one rule per environment, its canonical text, and its evaluation (docs/TEAM.md, "Policy").
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{TeamError, canon, id_ok};
|
||||
|
||||
/// One environment's rule.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct EnvRule {
|
||||
pub env: String,
|
||||
/// How many members must approve: 0 ..= 10. At 0 a test-role key signs without a card.
|
||||
pub approvals: u8,
|
||||
/// The approvers must not include the release's author, when the team has 2 or more members.
|
||||
pub others: bool,
|
||||
/// Member ids allowed to approve; empty = every member.
|
||||
pub approvers: Vec<String>,
|
||||
}
|
||||
|
||||
/// A team's policy.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Policy {
|
||||
pub team: String,
|
||||
pub rev: u32,
|
||||
pub envs: Vec<EnvRule>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct PolicyJson {
|
||||
v: u32,
|
||||
team: String,
|
||||
rev: u32,
|
||||
envs: Vec<EnvRule>,
|
||||
}
|
||||
|
||||
pub const MAX_APPROVALS: u8 = 10;
|
||||
pub const MAX_ENVS: usize = 8;
|
||||
|
||||
impl Policy {
|
||||
/// The default (docs/TEAM.md): preview 0, staging 1, production 1 by someone other than the author.
|
||||
pub fn default_for(team: &str) -> Policy {
|
||||
let rule = |env: &str, approvals, others| EnvRule { env: env.into(), approvals, others, approvers: vec![] };
|
||||
Policy {
|
||||
team: team.into(),
|
||||
rev: 1,
|
||||
envs: vec![rule("preview", 0, false), rule("staging", 1, false), rule("production", 1, true)],
|
||||
}
|
||||
}
|
||||
|
||||
pub fn rule(&self, env: &str) -> Option<&EnvRule> {
|
||||
self.envs.iter().find(|r| r.env == env)
|
||||
}
|
||||
|
||||
/// The canonical text the team identity signs.
|
||||
pub fn canonical(&self) -> String {
|
||||
let mut o = String::with_capacity(256);
|
||||
o.push_str("{\"v\":1,\"team\":");
|
||||
canon::string(&mut o, &self.team);
|
||||
o.push_str(",\"rev\":");
|
||||
o.push_str(&self.rev.to_string());
|
||||
o.push_str(",\"envs\":[");
|
||||
for (i, r) in self.envs.iter().enumerate() {
|
||||
if i > 0 {
|
||||
o.push(',');
|
||||
}
|
||||
o.push_str("{\"env\":");
|
||||
canon::string(&mut o, &r.env);
|
||||
o.push_str(",\"approvals\":");
|
||||
o.push_str(&r.approvals.to_string());
|
||||
o.push_str(",\"others\":");
|
||||
o.push_str(if r.others { "true" } else { "false" });
|
||||
o.push_str(",\"approvers\":");
|
||||
canon::strings(&mut o, &r.approvers);
|
||||
o.push('}');
|
||||
}
|
||||
o.push_str("]}");
|
||||
o
|
||||
}
|
||||
|
||||
/// Every rule as docs/TEAM.md allows it.
|
||||
pub fn check(&self) -> Result<(), TeamError> {
|
||||
let bad = |why| Err(TeamError::Invalid(why));
|
||||
if !id_ok(&self.team) {
|
||||
return bad("the policy's team is not an id");
|
||||
}
|
||||
if self.rev == 0 {
|
||||
return bad("the policy's rev starts at 1");
|
||||
}
|
||||
if self.envs.is_empty() || self.envs.len() > MAX_ENVS {
|
||||
return bad("a policy has 1 to 8 environments");
|
||||
}
|
||||
for (i, r) in self.envs.iter().enumerate() {
|
||||
if !canon::env_ok(&r.env) {
|
||||
return bad("an environment is not [a-z][a-z0-9-]{0,31}");
|
||||
}
|
||||
if self.envs[..i].iter().any(|o| o.env == r.env) {
|
||||
return bad("an environment is named twice");
|
||||
}
|
||||
if r.approvals > MAX_APPROVALS {
|
||||
return bad("at most 10 approvals");
|
||||
}
|
||||
if r.approvers.len() > crate::MAX_MEMBERS || !r.approvers.iter().all(|a| id_ok(a)) {
|
||||
return bad("approvers are member ids");
|
||||
}
|
||||
if r.approvers.iter().enumerate().any(|(j, a)| r.approvers[..j].contains(a)) {
|
||||
return bad("an approver is named twice");
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Reads a canonical policy text; anything else is refused, not normalised.
|
||||
pub fn parse(text: &str) -> Result<Policy, TeamError> {
|
||||
if text.len() > 16 * 1024 {
|
||||
return Err(TeamError::NotCanonical("a policy is at most 16 KiB"));
|
||||
}
|
||||
let j: PolicyJson = serde_json::from_str(text).map_err(|_| TeamError::NotCanonical("not a policy"))?;
|
||||
if j.v != 1 {
|
||||
return Err(TeamError::NotCanonical("v is not 1"));
|
||||
}
|
||||
let p = Policy { team: j.team, rev: j.rev, envs: j.envs };
|
||||
p.check()?;
|
||||
if p.canonical() != text {
|
||||
return Err(TeamError::NotCanonical("key order, spaces or escaping"));
|
||||
}
|
||||
Ok(p)
|
||||
}
|
||||
|
||||
/// Replaces (or adds) one environment's rule and raises `rev`.
|
||||
pub fn set_rule(&mut self, rule: EnvRule) -> Result<(), TeamError> {
|
||||
let mut next = self.clone();
|
||||
match next.envs.iter_mut().find(|r| r.env == rule.env) {
|
||||
Some(r) => *r = rule,
|
||||
None => next.envs.push(rule),
|
||||
}
|
||||
next.rev = self.rev.checked_add(1).ok_or(TeamError::Invalid("rev overflow"))?;
|
||||
next.check()?;
|
||||
*self = next;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// A member as the policy sees it: who they are and the names Fabrica knows them by.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct RosterMember {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub handles: Vec<String>,
|
||||
pub ed25519: [u8; 32],
|
||||
}
|
||||
|
||||
impl RosterMember {
|
||||
/// The member's id, or one of their handles (ASCII case-insensitive), names `author`.
|
||||
pub fn is(&self, author: &str) -> bool {
|
||||
!author.is_empty() && (self.id == author || self.handles.iter().any(|h| h.eq_ignore_ascii_case(author)))
|
||||
}
|
||||
}
|
||||
|
||||
/// Which kind of key a verdict allows.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum KeyRole {
|
||||
/// The environment asks for 1+ approvals and they are there: the release keys.
|
||||
Release,
|
||||
/// The environment asks for 0: a test-role key, no card.
|
||||
Test,
|
||||
}
|
||||
|
||||
impl KeyRole {
|
||||
pub fn word(self) -> &'static str {
|
||||
match self {
|
||||
KeyRole::Release => "release",
|
||||
KeyRole::Test => "test",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum Verdict {
|
||||
Allowed(KeyRole),
|
||||
/// This many more eligible approvals are needed.
|
||||
Need(u8),
|
||||
/// No set of approvals can ever meet the rule.
|
||||
Unsatisfiable(&'static str),
|
||||
UnknownEnv,
|
||||
}
|
||||
|
||||
/// The verdict and how it was reached.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Evaluation {
|
||||
pub verdict: Verdict,
|
||||
/// Members who may approve this request.
|
||||
pub eligible: Vec<String>,
|
||||
/// The approvals that counted, distinct, in the order given.
|
||||
pub counted: Vec<String>,
|
||||
/// Approvals that did not count: not on the roster, not eligible (the author, not an approver), a repeat.
|
||||
pub ignored: Vec<String>,
|
||||
}
|
||||
|
||||
impl Evaluation {
|
||||
pub fn into_result(self) -> Result<KeyRole, TeamError> {
|
||||
match self.verdict {
|
||||
Verdict::Allowed(r) => Ok(r),
|
||||
Verdict::Need(n) => Err(TeamError::NeedMore(n)),
|
||||
Verdict::Unsatisfiable(w) => Err(TeamError::Unsatisfiable(w)),
|
||||
Verdict::UnknownEnv => Err(TeamError::UnknownEnv),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Who may approve a request for `env` by `author`.
|
||||
pub fn eligible(policy: &Policy, roster: &[RosterMember], env: &str, author: &str) -> Option<Vec<String>> {
|
||||
let rule = policy.rule(env)?;
|
||||
let others = rule.others && roster.len() >= 2;
|
||||
Some(
|
||||
roster
|
||||
.iter()
|
||||
.filter(|m| rule.approvers.is_empty() || rule.approvers.contains(&m.id))
|
||||
.filter(|m| !(others && m.is(author)))
|
||||
.map(|m| m.id.clone())
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
|
||||
/// Evaluates the policy for one request (docs/TEAM.md, "Evaluation"). `approvers` are member ids whose approval
|
||||
/// statements were already checked.
|
||||
pub fn evaluate(policy: &Policy, roster: &[RosterMember], env: &str, author: &str, approvers: &[String]) -> Evaluation {
|
||||
let Some(rule) = policy.rule(env) else {
|
||||
return Evaluation { verdict: Verdict::UnknownEnv, eligible: vec![], counted: vec![], ignored: approvers.to_vec() };
|
||||
};
|
||||
let eligible = eligible(policy, roster, env, author).unwrap_or_default();
|
||||
let mut counted: Vec<String> = Vec::new();
|
||||
let mut ignored = Vec::new();
|
||||
for a in approvers {
|
||||
if eligible.contains(a) && !counted.contains(a) {
|
||||
counted.push(a.clone());
|
||||
} else {
|
||||
ignored.push(a.clone());
|
||||
}
|
||||
}
|
||||
let verdict = if rule.approvals == 0 {
|
||||
Verdict::Allowed(KeyRole::Test)
|
||||
} else if counted.len() >= rule.approvals as usize {
|
||||
Verdict::Allowed(KeyRole::Release)
|
||||
} else if eligible.len() < rule.approvals as usize {
|
||||
Verdict::Unsatisfiable(if rule.others && roster.len() >= 2 && eligible.is_empty() {
|
||||
"only the author may approve, and the rule needs someone else"
|
||||
} else {
|
||||
"the rule needs more approvals than there are members who may give them"
|
||||
})
|
||||
} else {
|
||||
Verdict::Need(rule.approvals - counted.len() as u8)
|
||||
};
|
||||
Evaluation { verdict, eligible, counted, ignored }
|
||||
}
|
||||
|
||||
/// Why `member` may not approve this request, or `Ok`.
|
||||
pub fn may_approve(
|
||||
policy: &Policy,
|
||||
roster: &[RosterMember],
|
||||
env: &str,
|
||||
author: &str,
|
||||
member: &str,
|
||||
) -> Result<(), TeamError> {
|
||||
let rule = policy.rule(env).ok_or(TeamError::UnknownEnv)?;
|
||||
let Some(me) = roster.iter().find(|m| m.id == member) else {
|
||||
return Err(TeamError::NotAMember);
|
||||
};
|
||||
if !rule.approvers.is_empty() && !rule.approvers.contains(&me.id) {
|
||||
return Err(TeamError::NotEligible("not on this environment's approver list"));
|
||||
}
|
||||
if rule.others && roster.len() >= 2 && me.is(author) {
|
||||
return Err(TeamError::NotEligible("the release's author may not approve it here"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,222 @@
|
||||
//! The policy proof (docs/TEAM.md, "The policy proof"): signed by the team identity, it says which request was
|
||||
//! signed under which policy, with whose approvals, by whom, and over which envelope. Anyone who pinned the team
|
||||
//! identity checks it with [`verify_proof`], which accepts only what the signing Custos itself would have signed.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::member::{TeamIdentity, verify_policy_sig, verify_proof_sig};
|
||||
use crate::policy::{KeyRole, Policy, RosterMember, evaluate};
|
||||
use crate::request::SignRequest;
|
||||
use crate::statement::{Statement, verified_members};
|
||||
use crate::{TeamError, b64, canon, hex, sha256, unb64, unhex};
|
||||
|
||||
/// The proof as it travels: its canonical text and the team identity's signature over it (base64).
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Proof {
|
||||
pub text: String,
|
||||
pub sig: String,
|
||||
}
|
||||
|
||||
/// A roster member as a proof lists them.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct RosterJson {
|
||||
id: String,
|
||||
name: String,
|
||||
handles: Vec<String>,
|
||||
ed25519: String,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct BodyJson {
|
||||
v: u32,
|
||||
team: String,
|
||||
request: String,
|
||||
env: String,
|
||||
author: String,
|
||||
policy: String,
|
||||
policy_sig: String,
|
||||
roster: Vec<RosterJson>,
|
||||
approvals: Vec<Statement>,
|
||||
signer: String,
|
||||
role: KeyRole,
|
||||
signature: String,
|
||||
at: u64,
|
||||
}
|
||||
|
||||
/// What a proof says, as the team's Custos builds it.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ProofBody {
|
||||
pub team: String,
|
||||
/// The request hash (hex).
|
||||
pub request: String,
|
||||
pub env: String,
|
||||
pub author: String,
|
||||
pub policy: String,
|
||||
pub policy_sig: [u8; 64],
|
||||
pub roster: Vec<RosterMember>,
|
||||
pub approvals: Vec<Statement>,
|
||||
pub signer: String,
|
||||
pub role: KeyRole,
|
||||
/// SHA-256 (hex) of the envelope that was returned.
|
||||
pub signature: String,
|
||||
pub at: u64,
|
||||
}
|
||||
|
||||
impl ProofBody {
|
||||
pub fn canonical(&self) -> String {
|
||||
let mut o = String::with_capacity(1024);
|
||||
o.push_str("{\"v\":1,\"team\":");
|
||||
canon::string(&mut o, &self.team);
|
||||
o.push_str(",\"request\":");
|
||||
canon::string(&mut o, &self.request);
|
||||
o.push_str(",\"env\":");
|
||||
canon::string(&mut o, &self.env);
|
||||
o.push_str(",\"author\":");
|
||||
canon::string(&mut o, &self.author);
|
||||
o.push_str(",\"policy\":");
|
||||
canon::string(&mut o, &self.policy);
|
||||
o.push_str(",\"policy_sig\":");
|
||||
canon::string(&mut o, &b64(&self.policy_sig));
|
||||
o.push_str(",\"roster\":[");
|
||||
for (i, m) in self.roster.iter().enumerate() {
|
||||
if i > 0 {
|
||||
o.push(',');
|
||||
}
|
||||
o.push_str("{\"id\":");
|
||||
canon::string(&mut o, &m.id);
|
||||
o.push_str(",\"name\":");
|
||||
canon::string(&mut o, &m.name);
|
||||
o.push_str(",\"handles\":");
|
||||
canon::strings(&mut o, &m.handles);
|
||||
o.push_str(",\"ed25519\":");
|
||||
canon::string(&mut o, &hex(&m.ed25519));
|
||||
o.push('}');
|
||||
}
|
||||
o.push_str("],\"approvals\":[");
|
||||
for (i, s) in self.approvals.iter().enumerate() {
|
||||
if i > 0 {
|
||||
o.push(',');
|
||||
}
|
||||
o.push_str("{\"member\":");
|
||||
canon::string(&mut o, &s.member);
|
||||
o.push_str(",\"code\":");
|
||||
canon::string(&mut o, &s.code);
|
||||
o.push_str(",\"at\":");
|
||||
o.push_str(&s.at.to_string());
|
||||
o.push_str(",\"sig\":");
|
||||
canon::string(&mut o, &s.sig);
|
||||
o.push('}');
|
||||
}
|
||||
o.push_str("],\"signer\":");
|
||||
canon::string(&mut o, &self.signer);
|
||||
o.push_str(",\"role\":");
|
||||
canon::string(&mut o, self.role.word());
|
||||
o.push_str(",\"signature\":");
|
||||
canon::string(&mut o, &self.signature);
|
||||
o.push_str(",\"at\":");
|
||||
o.push_str(&self.at.to_string());
|
||||
o.push('}');
|
||||
o
|
||||
}
|
||||
|
||||
/// Signed by the team identity.
|
||||
pub fn sign(&self, identity: &TeamIdentity) -> Proof {
|
||||
let text = self.canonical();
|
||||
let sig = identity.sign_proof(&text);
|
||||
Proof { text, sig: b64(&sig) }
|
||||
}
|
||||
|
||||
pub fn parse(text: &str) -> Result<ProofBody, TeamError> {
|
||||
if text.len() > 64 * 1024 {
|
||||
return Err(TeamError::NotCanonical("a proof is at most 64 KiB"));
|
||||
}
|
||||
let j: BodyJson = serde_json::from_str(text).map_err(|_| TeamError::NotCanonical("not a proof"))?;
|
||||
if j.v != 1 {
|
||||
return Err(TeamError::NotCanonical("v is not 1"));
|
||||
}
|
||||
let mut roster = Vec::new();
|
||||
for m in j.roster {
|
||||
let ed25519 = unhex::<32>(&m.ed25519).ok_or(TeamError::Invalid("a roster key is not 64 hex"))?;
|
||||
roster.push(RosterMember { id: m.id, name: m.name, handles: m.handles, ed25519 });
|
||||
}
|
||||
let body = ProofBody {
|
||||
team: j.team,
|
||||
request: j.request,
|
||||
env: j.env,
|
||||
author: j.author,
|
||||
policy: j.policy,
|
||||
policy_sig: unb64(&j.policy_sig)
|
||||
.and_then(|s| s.try_into().ok())
|
||||
.ok_or(TeamError::Invalid("policy_sig is not base64 of 64 bytes"))?,
|
||||
roster,
|
||||
approvals: j.approvals,
|
||||
signer: j.signer,
|
||||
role: j.role,
|
||||
signature: j.signature,
|
||||
at: j.at,
|
||||
};
|
||||
if body.canonical() != text {
|
||||
return Err(TeamError::NotCanonical("key order, spaces or escaping"));
|
||||
}
|
||||
Ok(body)
|
||||
}
|
||||
}
|
||||
|
||||
/// What a proof established.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Verified {
|
||||
pub role: KeyRole,
|
||||
pub env: String,
|
||||
pub signer: String,
|
||||
/// The approvals that counted under the policy.
|
||||
pub approvers: Vec<String>,
|
||||
pub policy_rev: u32,
|
||||
}
|
||||
|
||||
/// Checks a proof against the pinned team identity, the request it was made for and the envelope that came back
|
||||
/// with it: both signatures, every approval (signature, roster, the request's own match code), the request and
|
||||
/// envelope hashes, and the policy evaluated again. The clock is not consulted: a proof stays checkable after its
|
||||
/// request expired.
|
||||
pub fn verify_proof(proof: &Proof, identity: &[u8; 32], request_text: &str, envelope: &[u8]) -> Result<Verified, TeamError> {
|
||||
let sig: [u8; 64] = unb64(&proof.sig).and_then(|s| s.try_into().ok()).ok_or(TeamError::BadSignature)?;
|
||||
if !verify_proof_sig(identity, &proof.text, &sig) {
|
||||
return Err(TeamError::BadSignature);
|
||||
}
|
||||
let body = ProofBody::parse(&proof.text)?;
|
||||
let req = SignRequest::parse(request_text)?;
|
||||
if body.request != req.hash_hex() {
|
||||
return Err(TeamError::Invalid("the proof is for another request"));
|
||||
}
|
||||
if body.team != req.team || body.env != req.env || body.author != req.author {
|
||||
return Err(TeamError::Invalid("the proof does not match the request's team, env or author"));
|
||||
}
|
||||
if body.signature != hex(&sha256(envelope)) {
|
||||
return Err(TeamError::Invalid("the proof is for another signature"));
|
||||
}
|
||||
if !verify_policy_sig(identity, &body.policy, &body.policy_sig) {
|
||||
return Err(TeamError::BadSignature);
|
||||
}
|
||||
let policy = Policy::parse(&body.policy)?;
|
||||
if policy.team != body.team {
|
||||
return Err(TeamError::WrongTeam);
|
||||
}
|
||||
if !body.roster.iter().any(|m| m.id == body.signer) {
|
||||
return Err(TeamError::NotAMember);
|
||||
}
|
||||
for s in &body.approvals {
|
||||
s.verify(&req, &body.roster)?;
|
||||
}
|
||||
let approvers = verified_members(&body.approvals, &req, &body.roster);
|
||||
let eval = evaluate(&policy, &body.roster, &req.env, &req.author, &approvers);
|
||||
let role = eval.clone().into_result()?;
|
||||
if role != body.role {
|
||||
return Err(TeamError::Invalid("the proof's key role is not what the policy gives"));
|
||||
}
|
||||
if role == KeyRole::Release && !eval.counted.contains(&body.signer) {
|
||||
return Err(TeamError::Invalid("the signer's own approval is not among those that counted"));
|
||||
}
|
||||
Ok(Verified { role, env: body.env, signer: body.signer, approvers: eval.counted, policy_rev: policy.rev })
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
//! What goes back to Fabrica, sealed to the request's `pub` (docs/TEAM.md, "The reply").
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::proof::Proof;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct ReplyKey {
|
||||
pub id: String,
|
||||
/// `minisign.pub` text, `cosign.pub` PEM, or a certificate PEM.
|
||||
pub public: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct ReplySigner {
|
||||
pub member: String,
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
/// `sign.reply` v1.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct SignReply {
|
||||
pub v: u32,
|
||||
pub op: String,
|
||||
/// The request hash (hex).
|
||||
pub request: String,
|
||||
pub format: String,
|
||||
/// The envelope (docs/TEAM.md, "Signature envelopes").
|
||||
pub signature: String,
|
||||
/// cosign only: the payload that was signed.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub payload: Option<String>,
|
||||
pub key: ReplyKey,
|
||||
pub signer: ReplySigner,
|
||||
pub proof: Proof,
|
||||
}
|
||||
|
||||
impl SignReply {
|
||||
/// The bytes the proof's `signature` hashes: the envelope as text.
|
||||
pub fn envelope(&self) -> &[u8] {
|
||||
self.signature.as_bytes()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,334 @@
|
||||
//! The canonical `sign.request` and `target.request` (docs/TEAM.md, "The signing request"). Parsed, written again
|
||||
//! in canonical form and compared byte for byte: any other spelling is refused, not normalised.
|
||||
|
||||
use serde::Deserialize;
|
||||
|
||||
use crate::{MAX_AHEAD_SECS, TeamError, b64, canon, hex, id_ok, sha256, unb64};
|
||||
|
||||
/// The largest request text read.
|
||||
pub const MAX_REQUEST: usize = 4 * 1024;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Format {
|
||||
Minisign,
|
||||
TauriUpdater,
|
||||
Apk,
|
||||
Cosign,
|
||||
Authenticode,
|
||||
}
|
||||
|
||||
impl Format {
|
||||
pub fn word(self) -> &'static str {
|
||||
match self {
|
||||
Format::Minisign => "minisign",
|
||||
Format::TauriUpdater => "tauri-updater",
|
||||
Format::Apk => "apk",
|
||||
Format::Cosign => "cosign",
|
||||
Format::Authenticode => "authenticode",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_word(w: &str) -> Option<Format> {
|
||||
Some(match w {
|
||||
"minisign" => Format::Minisign,
|
||||
"tauri-updater" => Format::TauriUpdater,
|
||||
"apk" => Format::Apk,
|
||||
"cosign" => Format::Cosign,
|
||||
"authenticode" => Format::Authenticode,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether `digest` has this format's length (docs/TEAM.md, `artifact_digest`).
|
||||
pub fn digest_ok(self, digest: &[u8]) -> bool {
|
||||
match self {
|
||||
Format::Minisign | Format::TauriUpdater => digest.len() == 64,
|
||||
Format::Apk => !digest.is_empty() && digest.len() % 64 == 0 && digest.len() <= 64 * 4,
|
||||
Format::Cosign | Format::Authenticode => digest.len() == 32,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What the build claims about the file; shown on the card.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Artifact {
|
||||
pub name: String,
|
||||
pub size: u64,
|
||||
pub sha256: String,
|
||||
}
|
||||
|
||||
/// A checked `sign.request`.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct SignRequest {
|
||||
pub team: String,
|
||||
pub id: String,
|
||||
pub project: String,
|
||||
pub release: String,
|
||||
pub env: String,
|
||||
pub author: String,
|
||||
pub format: Format,
|
||||
pub artifact: Artifact,
|
||||
pub artifact_digest: Vec<u8>,
|
||||
pub image: String,
|
||||
pub public: [u8; 32],
|
||||
pub expires: u64,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct SignJson {
|
||||
v: u32,
|
||||
op: String,
|
||||
team: String,
|
||||
id: String,
|
||||
project: String,
|
||||
release: String,
|
||||
env: String,
|
||||
author: String,
|
||||
format: String,
|
||||
artifact: Artifact,
|
||||
artifact_digest: String,
|
||||
image: String,
|
||||
#[serde(rename = "pub")]
|
||||
public: String,
|
||||
expires: u64,
|
||||
}
|
||||
|
||||
fn lower_hex(s: &str, len: usize) -> bool {
|
||||
s.len() == len && s.bytes().all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c))
|
||||
}
|
||||
|
||||
pub(crate) fn pub_key(s: &str) -> Result<[u8; 32], TeamError> {
|
||||
let k: [u8; 32] = unb64(s)
|
||||
.and_then(|v| v.try_into().ok())
|
||||
.ok_or(TeamError::Invalid("pub is not base64 of 32 bytes"))?;
|
||||
if k == [0; 32] {
|
||||
return Err(TeamError::Invalid("pub is all zeros"));
|
||||
}
|
||||
Ok(k)
|
||||
}
|
||||
|
||||
fn name_ok(name: &str) -> bool {
|
||||
canon::text_ok(name, 200) && !name.contains(['/', '\\'])
|
||||
}
|
||||
|
||||
impl SignRequest {
|
||||
pub fn canonical(&self) -> String {
|
||||
let mut o = String::with_capacity(640);
|
||||
o.push_str("{\"v\":1,\"op\":\"sign.request\",\"team\":");
|
||||
canon::string(&mut o, &self.team);
|
||||
o.push_str(",\"id\":");
|
||||
canon::string(&mut o, &self.id);
|
||||
o.push_str(",\"project\":");
|
||||
canon::string(&mut o, &self.project);
|
||||
o.push_str(",\"release\":");
|
||||
canon::string(&mut o, &self.release);
|
||||
o.push_str(",\"env\":");
|
||||
canon::string(&mut o, &self.env);
|
||||
o.push_str(",\"author\":");
|
||||
canon::string(&mut o, &self.author);
|
||||
o.push_str(",\"format\":");
|
||||
canon::string(&mut o, self.format.word());
|
||||
o.push_str(",\"artifact\":{\"name\":");
|
||||
canon::string(&mut o, &self.artifact.name);
|
||||
o.push_str(",\"size\":");
|
||||
o.push_str(&self.artifact.size.to_string());
|
||||
o.push_str(",\"sha256\":");
|
||||
canon::string(&mut o, &self.artifact.sha256);
|
||||
o.push_str("},\"artifact_digest\":");
|
||||
canon::string(&mut o, &b64(&self.artifact_digest));
|
||||
o.push_str(",\"image\":");
|
||||
canon::string(&mut o, &self.image);
|
||||
o.push_str(",\"pub\":");
|
||||
canon::string(&mut o, &b64(&self.public));
|
||||
o.push_str(",\"expires\":");
|
||||
o.push_str(&self.expires.to_string());
|
||||
o.push('}');
|
||||
o
|
||||
}
|
||||
|
||||
/// Every field as docs/TEAM.md allows it, without the clock.
|
||||
pub fn check_fields(&self) -> Result<(), TeamError> {
|
||||
let bad = |w| Err(TeamError::Invalid(w));
|
||||
if !id_ok(&self.team) || !id_ok(&self.id) {
|
||||
return bad("team and id are 32 lower-case hex digits");
|
||||
}
|
||||
if !canon::ascii_ok(&self.project, 1, 128, b"._/-") {
|
||||
return bad("project is 1 to 128 of [A-Za-z0-9._/-]");
|
||||
}
|
||||
if !canon::ascii_ok(&self.release, 1, 64, b"._+-") {
|
||||
return bad("release is 1 to 64 of [A-Za-z0-9._+-]");
|
||||
}
|
||||
if !canon::env_ok(&self.env) {
|
||||
return bad("env is [a-z][a-z0-9-]{0,31}");
|
||||
}
|
||||
if !canon::ascii_ok(&self.author, 0, 64, b"._@-") {
|
||||
return bad("author is 0 to 64 of [A-Za-z0-9._@-]");
|
||||
}
|
||||
if !name_ok(&self.artifact.name) {
|
||||
return bad("the artifact's name is 1 to 200 characters, no path, no control characters");
|
||||
}
|
||||
if !lower_hex(&self.artifact.sha256, 64) {
|
||||
return bad("the artifact's sha256 is 64 lower-case hex digits");
|
||||
}
|
||||
if !self.format.digest_ok(&self.artifact_digest) {
|
||||
return bad("artifact_digest has the wrong length for its format");
|
||||
}
|
||||
match self.format {
|
||||
Format::Cosign => custos_sign::image_ok(&self.image).map_err(|_| TeamError::Invalid("image is not a repository"))?,
|
||||
_ if !self.image.is_empty() => return bad("image is for cosign only"),
|
||||
_ => {}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Reads a canonical request, without the clock: for showing what an expired request said. Never enough to sign.
|
||||
pub fn parse(text: &str) -> Result<SignRequest, TeamError> {
|
||||
if text.len() > MAX_REQUEST {
|
||||
return Err(TeamError::NotCanonical("a request is at most 4 KiB"));
|
||||
}
|
||||
let j: SignJson = serde_json::from_str(text).map_err(|_| TeamError::NotCanonical("not a sign.request"))?;
|
||||
if j.v != 1 || j.op != "sign.request" {
|
||||
return Err(TeamError::NotCanonical("not a sign.request v1"));
|
||||
}
|
||||
let format = Format::from_word(&j.format).ok_or(TeamError::Invalid("an unknown format"))?;
|
||||
let digest = unb64(&j.artifact_digest).ok_or(TeamError::Invalid("artifact_digest is not base64"))?;
|
||||
let r = SignRequest {
|
||||
team: j.team,
|
||||
id: j.id,
|
||||
project: j.project,
|
||||
release: j.release,
|
||||
env: j.env,
|
||||
author: j.author,
|
||||
format,
|
||||
artifact: j.artifact,
|
||||
artifact_digest: digest,
|
||||
image: j.image,
|
||||
public: pub_key(&j.public)?,
|
||||
expires: j.expires,
|
||||
};
|
||||
r.check_fields()?;
|
||||
if r.canonical() != text {
|
||||
return Err(TeamError::NotCanonical("key order, spaces or escaping"));
|
||||
}
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
/// [`SignRequest::parse`] and the clock: not expired at `now` (Unix seconds), at most 25 hours ahead.
|
||||
pub fn check(text: &str, now: u64) -> Result<SignRequest, TeamError> {
|
||||
let r = SignRequest::parse(text)?;
|
||||
if r.expires <= now {
|
||||
return Err(TeamError::Expired);
|
||||
}
|
||||
if r.expires > now.saturating_add(MAX_AHEAD_SECS) {
|
||||
return Err(TeamError::Invalid("it expires more than 25 hours from now"));
|
||||
}
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
/// SHA-256 of the canonical text.
|
||||
pub fn hash(&self) -> [u8; 32] {
|
||||
sha256(self.canonical().as_bytes())
|
||||
}
|
||||
|
||||
pub fn hash_hex(&self) -> String {
|
||||
hex(&self.hash())
|
||||
}
|
||||
|
||||
/// The match code Fabrica shows and every card shows: `match_code(pub)`.
|
||||
pub fn match_code(&self) -> String {
|
||||
custos_seal::match_code(&self.public)
|
||||
}
|
||||
|
||||
/// The context the reply is sealed under.
|
||||
pub fn reply_context(&self) -> Vec<u8> {
|
||||
format!("team-sign:{}", self.id).into_bytes()
|
||||
}
|
||||
}
|
||||
|
||||
/// Fabrica asks for a target credential for one deployment (docs/TEAM.md, "Target credentials").
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct TargetRequest {
|
||||
pub team: String,
|
||||
pub id: String,
|
||||
pub target: String,
|
||||
/// The hash of the `sign.request` whose signature this deployment deploys.
|
||||
pub deployment: String,
|
||||
pub public: [u8; 32],
|
||||
pub expires: u64,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct TargetJson {
|
||||
v: u32,
|
||||
op: String,
|
||||
team: String,
|
||||
id: String,
|
||||
target: String,
|
||||
deployment: String,
|
||||
#[serde(rename = "pub")]
|
||||
public: String,
|
||||
expires: u64,
|
||||
}
|
||||
|
||||
impl TargetRequest {
|
||||
pub fn canonical(&self) -> String {
|
||||
let mut o = String::with_capacity(256);
|
||||
o.push_str("{\"v\":1,\"op\":\"target.request\",\"team\":");
|
||||
canon::string(&mut o, &self.team);
|
||||
o.push_str(",\"id\":");
|
||||
canon::string(&mut o, &self.id);
|
||||
o.push_str(",\"target\":");
|
||||
canon::string(&mut o, &self.target);
|
||||
o.push_str(",\"deployment\":");
|
||||
canon::string(&mut o, &self.deployment);
|
||||
o.push_str(",\"pub\":");
|
||||
canon::string(&mut o, &b64(&self.public));
|
||||
o.push_str(",\"expires\":");
|
||||
o.push_str(&self.expires.to_string());
|
||||
o.push('}');
|
||||
o
|
||||
}
|
||||
|
||||
/// Reads and checks a canonical target request at `now`; it lives at most 25 hours.
|
||||
pub fn check(text: &str, now: u64) -> Result<TargetRequest, TeamError> {
|
||||
if text.len() > MAX_REQUEST {
|
||||
return Err(TeamError::NotCanonical("a request is at most 4 KiB"));
|
||||
}
|
||||
let j: TargetJson = serde_json::from_str(text).map_err(|_| TeamError::NotCanonical("not a target.request"))?;
|
||||
if j.v != 1 || j.op != "target.request" {
|
||||
return Err(TeamError::NotCanonical("not a target.request v1"));
|
||||
}
|
||||
let r = TargetRequest {
|
||||
team: j.team,
|
||||
id: j.id,
|
||||
target: j.target,
|
||||
deployment: j.deployment,
|
||||
public: pub_key(&j.public)?,
|
||||
expires: j.expires,
|
||||
};
|
||||
if !id_ok(&r.team) || !id_ok(&r.id) || !lower_hex(&r.target, 16) || !lower_hex(&r.deployment, 64) {
|
||||
return Err(TeamError::Invalid("team, id, target and deployment are hex ids"));
|
||||
}
|
||||
if r.canonical() != text {
|
||||
return Err(TeamError::NotCanonical("key order, spaces or escaping"));
|
||||
}
|
||||
if r.expires <= now {
|
||||
return Err(TeamError::Expired);
|
||||
}
|
||||
if r.expires > now.saturating_add(MAX_AHEAD_SECS) {
|
||||
return Err(TeamError::Invalid("it expires more than 25 hours from now"));
|
||||
}
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
pub fn match_code(&self) -> String {
|
||||
custos_seal::match_code(&self.public)
|
||||
}
|
||||
|
||||
pub fn reply_context(&self) -> Vec<u8> {
|
||||
format!("team-target:{}", self.id).into_bytes()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
//! A member's approval of one request (docs/TEAM.md, "Approval statements").
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::member::MemberKey;
|
||||
use crate::policy::RosterMember;
|
||||
use crate::request::SignRequest;
|
||||
use crate::{TeamError, b64, unb64, unhex};
|
||||
|
||||
pub const APPROVAL_DOMAIN: &[u8] = b"custos team approval v1\0";
|
||||
|
||||
/// `{"member", "code", "at", "sig"}`: who approved which request (by its hash, outside), with which code, when.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Statement {
|
||||
pub member: String,
|
||||
pub code: String,
|
||||
pub at: u64,
|
||||
/// Base64 of the 64-byte Ed25519 signature.
|
||||
pub sig: String,
|
||||
}
|
||||
|
||||
/// What a statement signs.
|
||||
pub fn message(request_hash: &[u8; 32], code: &str, member: &[u8; 16], at: u64) -> Vec<u8> {
|
||||
let mut m = Vec::with_capacity(APPROVAL_DOMAIN.len() + 32 + 6 + 16 + 8);
|
||||
m.extend_from_slice(APPROVAL_DOMAIN);
|
||||
m.extend_from_slice(request_hash);
|
||||
m.extend_from_slice(code.as_bytes());
|
||||
m.extend_from_slice(member);
|
||||
m.extend_from_slice(&at.to_be_bytes());
|
||||
m
|
||||
}
|
||||
|
||||
fn code_ok(code: &str) -> bool {
|
||||
code.len() == 6 && code.bytes().all(|c| c.is_ascii_digit())
|
||||
}
|
||||
|
||||
/// A member approves `req`. `shown_code` is the code the card showed: when it is not the request's own match code,
|
||||
/// the request changed after the card was drawn, or it is someone else's, and nothing is signed (`WrongMatch`).
|
||||
pub fn approve(key: &MemberKey, req: &SignRequest, shown_code: &str, now: u64) -> Result<Statement, TeamError> {
|
||||
if shown_code != req.match_code() {
|
||||
return Err(TeamError::WrongMatch);
|
||||
}
|
||||
let id = key.public().id_bytes();
|
||||
let sig = key.sign(&message(&req.hash(), shown_code, &id, now));
|
||||
Ok(Statement { member: key.id(), code: shown_code.into(), at: now, sig: b64(&sig) })
|
||||
}
|
||||
|
||||
impl Statement {
|
||||
/// Checks this statement for `req` against the roster: the member is on it, the code is the request's own,
|
||||
/// the signature is the member's.
|
||||
pub fn verify(&self, req: &SignRequest, roster: &[RosterMember]) -> Result<(), TeamError> {
|
||||
if !code_ok(&self.code) || self.code != req.match_code() {
|
||||
return Err(TeamError::WrongMatch);
|
||||
}
|
||||
let m = roster.iter().find(|m| m.id == self.member).ok_or(TeamError::NotAMember)?;
|
||||
let id: [u8; 16] = unhex(&self.member).ok_or(TeamError::NotAMember)?;
|
||||
let sig: [u8; 64] =
|
||||
unb64(&self.sig).and_then(|s| s.try_into().ok()).ok_or(TeamError::BadSignature)?;
|
||||
if !crate::member::verify(&m.ed25519, &message(&req.hash(), &self.code, &id, self.at), &sig) {
|
||||
return Err(TeamError::BadSignature);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// The member ids of the statements that verify for `req`, each once, in order; the others are dropped.
|
||||
pub fn verified_members(statements: &[Statement], req: &SignRequest, roster: &[RosterMember]) -> Vec<String> {
|
||||
let mut out: Vec<String> = Vec::new();
|
||||
for s in statements {
|
||||
if s.verify(req, roster).is_ok() && !out.contains(&s.member) {
|
||||
out.push(s.member.clone());
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
//! Target credentials (docs/TEAM.md, "Target credentials"): what they are, and the plaintext a released one is
|
||||
//! sealed as.
|
||||
|
||||
use std::fmt;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
pub enum TargetKind {
|
||||
/// An OpenSSH private key.
|
||||
SshKey,
|
||||
/// A WinRM user and password.
|
||||
Winrm,
|
||||
/// An OpenSSH user and password.
|
||||
Openssh,
|
||||
/// A Docker registry token.
|
||||
Registry,
|
||||
/// A kubeconfig.
|
||||
Kubeconfig,
|
||||
}
|
||||
|
||||
impl TargetKind {
|
||||
pub fn word(self) -> &'static str {
|
||||
match self {
|
||||
TargetKind::SshKey => "ssh-key",
|
||||
TargetKind::Winrm => "winrm",
|
||||
TargetKind::Openssh => "openssh",
|
||||
TargetKind::Registry => "registry",
|
||||
TargetKind::Kubeconfig => "kubeconfig",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The largest target credential.
|
||||
pub const MAX_SECRET: usize = 64 * 1024;
|
||||
|
||||
/// A released credential, as sealed to the Fabrica server's one-time key (`team-target:<request id>`).
|
||||
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct TargetRelease {
|
||||
pub v: u32,
|
||||
pub op: String,
|
||||
pub team: String,
|
||||
pub target: String,
|
||||
pub kind: TargetKind,
|
||||
pub name: String,
|
||||
pub host: String,
|
||||
pub user: String,
|
||||
pub secret: String,
|
||||
/// The deployment's request hash.
|
||||
pub deployment: String,
|
||||
pub project: String,
|
||||
pub env: String,
|
||||
}
|
||||
|
||||
impl fmt::Debug for TargetRelease {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("TargetRelease")
|
||||
.field("target", &self.target)
|
||||
.field("kind", &self.kind)
|
||||
.field("deployment", &self.deployment)
|
||||
.field("secret", &"[redacted]")
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user