1use std::collections::{BTreeMap, BTreeSet};
13
14use alien_error::AlienError;
15use serde::{Deserialize, Serialize};
16
17use crate::envelope::{Kind, Opened, Role, SignedStatement};
18use crate::error::{ErrorData, Result};
19use crate::key::PublicKey;
20
21pub const MAX_SIGNERS: usize = 256;
23
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
26#[serde(rename_all = "camelCase")]
27pub enum SignerKind {
28 Ci,
30 Device,
33 Recovery,
35}
36
37#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
39#[serde(rename_all = "kebab-case")]
40pub enum KeyBackend {
41 SecureEnclave,
43 Tpm,
45 Yubikey,
47 Software,
49}
50
51impl KeyBackend {
52 pub fn as_str(self) -> &'static str {
54 match self {
55 Self::SecureEnclave => "secure-enclave",
56 Self::Tpm => "tpm",
57 Self::Yubikey => "yubikey",
58 Self::Software => "software",
59 }
60 }
61}
62
63#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
65#[serde(rename_all = "camelCase", deny_unknown_fields)]
66pub struct Signer {
67 pub id: String,
69 pub key: String,
71 pub kind: SignerKind,
73 #[serde(default, skip_serializing_if = "Option::is_none")]
75 pub backend: Option<KeyBackend>,
76 pub roles: Vec<Role>,
78 #[serde(default, skip_serializing_if = "Option::is_none")]
80 pub label: Option<String>,
81}
82
83pub fn release_deny_entry(sequence: u64) -> String {
86 format!("release:{sequence}")
87}
88
89#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
91#[serde(rename_all = "camelCase")]
92pub enum KeptKind {
93 Release,
95 Config,
97}
98
99impl KeptKind {
100 pub fn kind(self) -> Kind {
102 match self {
103 Self::Release => Kind::Release,
104 Self::Config => Kind::Config,
105 }
106 }
107
108 pub fn as_str(self) -> &'static str {
110 match self {
111 Self::Release => "release",
112 Self::Config => "config",
113 }
114 }
115}
116
117pub const MAX_KEEP: usize = 4096;
119
120#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
125#[serde(rename_all = "camelCase", deny_unknown_fields)]
126pub struct Keep {
127 pub digest: String,
129 pub kind: KeptKind,
131 #[serde(default, skip_serializing_if = "Option::is_none")]
135 pub release_id: Option<String>,
136 pub sequence: u64,
138}
139
140#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
142#[serde(rename_all = "camelCase", deny_unknown_fields)]
143pub struct SignerListBody {
144 pub previous: Option<String>,
146 pub admin_threshold: u32,
148 pub signers: Vec<Signer>,
150 #[serde(default, skip_serializing_if = "Vec::is_empty")]
154 pub deny: Vec<String>,
155 #[serde(default, skip_serializing_if = "Vec::is_empty")]
159 pub keep: Vec<Keep>,
160 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
163 pub recovered: bool,
164}
165
166impl SignerListBody {
167 pub fn refuses(&self, opened: &crate::envelope::Opened) -> bool {
170 self.deny.contains(&opened.digest)
171 || (opened.kind == crate::envelope::Kind::Release
172 && self.deny.contains(&release_deny_entry(opened.sequence)))
173 }
174
175 pub fn keeps(&self, opened: &crate::envelope::Opened) -> bool {
178 self.keep.iter().any(|kept| {
179 kept.digest == opened.digest
180 && kept.kind.kind() == opened.kind
181 && kept.sequence == opened.sequence
182 })
183 }
184}
185
186#[derive(Debug, Clone)]
188pub struct TrustedList {
189 pub version: u64,
191 pub digest: String,
193 pub body: SignerListBody,
195 keys: BTreeMap<String, (PublicKey, BTreeSet<Role>)>,
196}
197
198impl TrustedList {
199 pub fn signer(&self, id: &str) -> Option<(&PublicKey, &BTreeSet<Role>)> {
201 self.keys.get(id).map(|(key, roles)| (key, roles))
202 }
203
204 pub fn signer_kind(&self, id: &str) -> Option<SignerKind> {
206 self.body
207 .signers
208 .iter()
209 .find(|signer| signer.id == id)
210 .map(|signer| signer.kind)
211 }
212
213 pub fn denies(&self, digest: &str) -> bool {
215 self.body.deny.iter().any(|denied| denied == digest)
216 }
217
218 pub fn keeps(&self, opened: &crate::envelope::Opened) -> bool {
220 self.body.keeps(opened)
221 }
222
223 pub fn refuses(&self, opened: &crate::envelope::Opened) -> bool {
225 self.body.refuses(opened)
226 }
227
228 pub fn check_signatures(&self, opened: &Opened, role: Role) -> Result<BTreeSet<String>> {
233 let mut signers = BTreeSet::new();
234 for signature in &opened.signatures {
235 let (key, roles) = self.signer(&signature.signer).ok_or_else(|| {
236 refused_signature(
237 &signature.signer,
238 format!("not on signer list version {}", self.version),
239 )
240 })?;
241 if !roles.contains(&role) {
242 return Err(refused_signature(
243 &signature.signer,
244 format!("does not hold the '{}' role", role.as_str()),
245 ));
246 }
247 key.verify(&opened.bytes, &signature.sig)
248 .map_err(|error| refused_signature(&signature.signer, error.message))?;
249 if !signers.insert(signature.signer.clone()) {
250 return Err(refused_signature(
251 &signature.signer,
252 "signed twice".to_string(),
253 ));
254 }
255 }
256 if signers.is_empty() {
257 return Err(AlienError::new(ErrorData::Unsigned {
258 role: role.as_str().to_string(),
259 }));
260 }
261 Ok(signers)
262 }
263
264 fn admin_count(&self) -> usize {
265 self.keys
266 .values()
267 .filter(|(_, roles)| roles.contains(&Role::Admin))
268 .count()
269 }
270}
271
272#[derive(Debug, Clone)]
275pub struct SignerChain {
276 project: String,
277 statements: Vec<SignedStatement>,
278 digests: Vec<String>,
279 lists: Vec<TrustedList>,
281}
282
283impl SignerChain {
284 pub fn genesis(fingerprint: &str, statement: &SignedStatement) -> Result<Self> {
287 let opened = statement.open()?;
288 let version = opened.sequence;
289 let expected = fingerprint_digest(fingerprint)?;
290 let project = opened.project.clone();
291 if opened.digest != expected {
292 return Err(list_refused(
293 version,
294 format!(
295 "its digest {} does not match the pinned fingerprint {fingerprint}",
296 opened.digest
297 ),
298 ));
299 }
300 let list = parse_list(&project, &opened, 1)?;
301 if list.body.previous.is_some() {
302 return Err(list_refused(1, "version 1 names a previous version"));
303 }
304 if list.body.recovered {
305 return Err(list_refused(1, "version 1 can't be a recovery"));
306 }
307 let signers = list.check_signatures(&opened, Role::Admin)?;
308 if signers.len() < list.body.admin_threshold as usize {
309 return Err(list_refused(
310 1,
311 format!(
312 "signed by {} of its own admins, below its threshold of {}",
313 signers.len(),
314 list.body.admin_threshold
315 ),
316 ));
317 }
318 Ok(Self {
319 project,
320 statements: vec![statement.clone()],
321 digests: vec![opened.digest],
322 lists: vec![list],
323 })
324 }
325
326 pub fn from_statements(fingerprint: &str, statements: &[SignedStatement]) -> Result<Self> {
328 let mut opened = statements
329 .iter()
330 .map(|statement| statement.open().map(|opened| (opened.sequence, statement)))
331 .collect::<Result<Vec<_>>>()?;
332 opened.sort_by_key(|(sequence, _)| *sequence);
333 let ((_, first), rest) = opened
334 .split_first()
335 .ok_or_else(|| list_refused(1, "the chain is empty"))?;
336 let mut chain = Self::genesis(fingerprint, first)?;
337 let rest: Vec<SignedStatement> = rest
338 .iter()
339 .map(|(_, statement)| (*statement).clone())
340 .collect();
341 chain.extend(&rest)?;
342 Ok(chain)
343 }
344
345 pub fn digest_of(&self, version: u64) -> Option<&str> {
347 version
348 .checked_sub(1)
349 .and_then(|index| self.digests.get(index as usize))
350 .map(String::as_str)
351 }
352
353 pub fn current(&self) -> &TrustedList {
355 self.lists.last().expect("a chain holds version 1")
356 }
357
358 pub fn version(&self, version: u64) -> Option<&TrustedList> {
360 version
361 .checked_sub(1)
362 .and_then(|index| self.lists.get(index as usize))
363 }
364
365 pub fn project(&self) -> &str {
367 &self.project
368 }
369
370 pub fn statements(&self) -> &[SignedStatement] {
372 &self.statements
373 }
374
375 pub fn extend(&mut self, statements: &[SignedStatement]) -> Result<bool> {
382 let mut opened = statements
383 .iter()
384 .map(|statement| statement.open().map(|opened| (opened, statement)))
385 .collect::<Result<Vec<_>>>()?;
386 opened.sort_by_key(|(opened, _)| opened.sequence);
387 let before = self.current().version;
388 for (opened, statement) in opened {
389 if opened.kind != Kind::SignerList {
390 return Err(list_refused(
391 opened.sequence,
392 format!("it is a '{}' statement", opened.kind),
393 ));
394 }
395 let version = opened.sequence;
396 if version <= self.current().version {
397 if self.digest_of(version) != Some(opened.digest.as_str()) {
398 return Err(list_refused(
399 version,
400 "a different list with this version is already trusted",
401 ));
402 }
403 continue;
404 }
405 self.advance(&opened, statement)?;
406 }
407 Ok(self.current().version > before)
408 }
409
410 fn advance(&mut self, opened: &Opened, statement: &SignedStatement) -> Result<()> {
411 let version = opened.sequence;
412 if version != self.current().version + 1 {
413 return Err(list_refused(
414 version,
415 format!(
416 "version {} is missing; the chain is at version {}",
417 self.current().version + 1,
418 self.current().version
419 ),
420 ));
421 }
422 let next = parse_list(&self.project, opened, self.current().version)?;
423 if next.body.previous.as_deref() != Some(self.current().digest.as_str()) {
424 return Err(list_refused(
425 version,
426 format!(
427 "it does not name version {}'s digest",
428 self.current().version
429 ),
430 ));
431 }
432 let signers = self.current().check_signatures(opened, Role::Admin)?;
433 let threshold = self.current().body.admin_threshold as usize;
434 if signers.len() < threshold {
435 return Err(list_refused(
436 version,
437 format!(
438 "signed by {} admins of version {}, below its threshold of {threshold}",
439 signers.len(),
440 self.current().version
441 ),
442 ));
443 }
444 let by_recovery = signers
445 .iter()
446 .any(|signer| self.current().signer_kind(signer) == Some(SignerKind::Recovery));
447 if by_recovery != next.body.recovered {
448 return Err(list_refused(
449 version,
450 if by_recovery {
451 "the recovery key signed it, but it isn't marked recovered"
452 } else {
453 "it is marked recovered, but the recovery key didn't sign it"
454 },
455 ));
456 }
457 self.statements.push(statement.clone());
458 self.digests.push(opened.digest.clone());
459 self.lists.push(next);
460 Ok(())
461 }
462}
463
464pub fn fingerprint(digest: &str) -> String {
466 format!(
467 "SHA256:{}",
468 digest.strip_prefix("sha256:").unwrap_or(digest)
469 )
470}
471
472pub fn display_fingerprint(fingerprint: &str) -> String {
475 let hex_part = fingerprint.strip_prefix("SHA256:").unwrap_or(fingerprint);
476 hex_part
477 .as_bytes()
478 .chunks(4)
479 .take(8)
480 .map(|chunk| String::from_utf8_lossy(chunk).to_uppercase())
481 .collect::<Vec<_>>()
482 .join(" ")
483}
484
485pub fn is_fingerprint(fingerprint: &str) -> bool {
487 fingerprint_digest(fingerprint).is_ok()
488}
489
490fn fingerprint_digest(fingerprint: &str) -> Result<String> {
491 let hex_part = fingerprint
492 .strip_prefix("SHA256:")
493 .filter(|hex_part| {
494 hex_part.len() == 64
495 && hex_part
496 .bytes()
497 .all(|byte| matches!(byte, b'0'..=b'9' | b'a'..=b'f'))
498 })
499 .ok_or_else(|| {
500 AlienError::new(ErrorData::SettingsInvalid {
501 reason: format!("fingerprint '{fingerprint}' is not SHA256:<64 lowercase hex>"),
502 })
503 })?;
504 Ok(format!("sha256:{hex_part}"))
505}
506
507fn parse_list(project: &str, opened: &Opened, authorizing_version: u64) -> Result<TrustedList> {
508 let version = opened.sequence;
509 if opened.kind != Kind::SignerList {
510 return Err(list_refused(
511 version,
512 format!("it is a '{}' statement", opened.kind),
513 ));
514 }
515 if opened.project != project || project.is_empty() {
516 return Err(AlienError::new(ErrorData::WrongProject {
517 expected: project.to_string(),
518 actual: opened.project.clone(),
519 }));
520 }
521 if opened.install.is_some() {
522 return Err(list_refused(version, "a signer list names no install"));
523 }
524 if opened.not_after.is_some() {
525 return Err(list_refused(
528 version,
529 "it has an expiry date, so an Alien CLI older than 3.3.69 published it. \
530 Signer lists no longer expire. Run `alien devices init` to start signing \
531 again, then re-run the protected setup with the new fingerprint",
532 ));
533 }
534 if version == 0 {
535 return Err(list_refused(version, "versions start at 1"));
536 }
537 if opened.signer_list_version != authorizing_version {
538 return Err(list_refused(
539 version,
540 format!(
541 "it says it is authorized by version {}, not {authorizing_version}",
542 opened.signer_list_version
543 ),
544 ));
545 }
546 let body: SignerListBody = opened.body()?;
547 if body.signers.len() > MAX_SIGNERS {
548 return Err(list_refused(
549 version,
550 format!("more than {MAX_SIGNERS} signers"),
551 ));
552 }
553 if body.keep.len() > MAX_KEEP {
554 return Err(list_refused(
555 version,
556 format!("more than {MAX_KEEP} kept statements"),
557 ));
558 }
559 let mut kept_digests = BTreeSet::new();
560 for kept in &body.keep {
561 if !crate::release::is_sha256_digest(&kept.digest) {
562 return Err(list_refused(
563 version,
564 format!("kept '{}' is not a digest", kept.digest),
565 ));
566 }
567 if !kept_digests.insert(kept.digest.as_str()) {
568 return Err(list_refused(
569 version,
570 format!("{} is kept twice", kept.digest),
571 ));
572 }
573 }
574 let mut keys = BTreeMap::new();
575 let mut key_texts = BTreeSet::new();
576 for signer in &body.signers {
577 if !valid_signer_id(&signer.id) {
578 return Err(list_refused(
579 version,
580 format!("signer id '{}' is not 1-64 of [a-z0-9-]", signer.id),
581 ));
582 }
583 let key = PublicKey::parse(&signer.key).map_err(|error| {
584 list_refused(
585 version,
586 format!("signer '{}': {}", signer.id, error.message),
587 )
588 })?;
589 if !key_texts.insert(key.as_str().to_string()) {
590 return Err(list_refused(
591 version,
592 format!("signer '{}' reuses a key already on the list", signer.id),
593 ));
594 }
595 let roles: BTreeSet<Role> = signer.roles.iter().copied().collect();
596 if roles.is_empty() || roles.len() != signer.roles.len() {
597 return Err(list_refused(
598 version,
599 format!("signer '{}' has no roles or repeats one", signer.id),
600 ));
601 }
602 if keys.insert(signer.id.clone(), (key, roles)).is_some() {
603 return Err(list_refused(
604 version,
605 format!("signer id '{}' appears twice", signer.id),
606 ));
607 }
608 }
609 let list = TrustedList {
610 version,
611 digest: opened.digest.clone(),
612 body,
613 keys,
614 };
615 let admins = list.admin_count();
616 let threshold = list.body.admin_threshold as usize;
617 if threshold == 0 || threshold > admins {
618 return Err(list_refused(
619 version,
620 format!("admin threshold {threshold} must be between 1 and its {admins} admins"),
621 ));
622 }
623 Ok(list)
624}
625
626fn valid_signer_id(id: &str) -> bool {
627 (1..=64).contains(&id.len())
628 && id
629 .bytes()
630 .all(|byte| matches!(byte, b'a'..=b'z' | b'0'..=b'9' | b'-'))
631}
632
633fn list_refused(version: u64, reason: impl Into<String>) -> AlienError<ErrorData> {
634 AlienError::new(ErrorData::SignerListRefused {
635 version,
636 reason: reason.into(),
637 })
638}
639
640fn refused_signature(signer: &str, reason: String) -> AlienError<ErrorData> {
641 AlienError::new(ErrorData::SignatureRefused {
642 signer: signer.to_string(),
643 reason,
644 })
645}