291 lines
10 KiB
Rust
291 lines
10 KiB
Rust
//! 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());
|
|
}
|
|
}
|
|
// `others` needs to know who the author is (core 0.18.1): an empty author, or one no member is, would let the
|
|
// author approve their own release under a name the rule cannot see.
|
|
let unknown_author = rule.others && roster.len() >= 2 && !roster.iter().any(|m| m.is(author));
|
|
let verdict = if rule.approvals == 0 {
|
|
Verdict::Allowed(KeyRole::Test)
|
|
} else if unknown_author {
|
|
Verdict::Unsatisfiable("the release's author is not a member the team knows, so the rule cannot exclude them")
|
|
} 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"));
|
|
}
|
|
if rule.approvals > 0 && rule.others && roster.len() >= 2 && !roster.iter().any(|m| m.is(author)) {
|
|
return Err(TeamError::NotEligible("the release's author is not a member the team knows"));
|
|
}
|
|
Ok(())
|
|
}
|