Skip to main content

pic_continuity/artifacts/
pca.rs

1/*
2 * Copyright Nitro Agility S.r.l.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      https://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17//! PIC PCA COSE (`pic-pca+cose`): the signed trusted authority checkpoint.
18
19use super::check_profile;
20use crate::authority::indexed::IndexedAuthorityMap;
21use crate::cose::CoseSigned;
22use crate::error::RejectReason;
23use serde::{Deserialize, Serialize};
24
25/// Challenge state carried by a PCA checkpoint: the challenge the next
26/// transition must answer.
27#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
28pub struct PcaChallenge {
29    /// The verifier-issued challenge the next transition must echo as its
30    /// `previous_challenge`.
31    #[serde(with = "serde_bytes")]
32    pub next_challenge: Vec<u8>,
33}
34
35/// PIC PCA COSE payload: the signed trusted authority checkpoint.
36#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
37pub struct PicPcaPayload {
38    /// PIC profile identifier; must equal [`crate::PROFILE_0_2`].
39    pub profile: String,
40    /// Position of this checkpoint in its lineage, starting at `0`.
41    pub position: u64,
42    /// The canonical Indexed Authority Map in force at this checkpoint.
43    pub context_of_authority: IndexedAuthorityMap,
44    /// Challenge state binding the next transition to this checkpoint.
45    pub challenge: PcaChallenge,
46}
47
48impl PicPcaPayload {
49    /// A Profile 0.2 checkpoint payload at `position` carrying `context`
50    /// and the verifier-issued `next_challenge`.
51    pub fn new(position: u64, context: IndexedAuthorityMap, next_challenge: Vec<u8>) -> Self {
52        Self {
53            profile: crate::PROFILE_0_2.to_string(),
54            position,
55            context_of_authority: context,
56            challenge: PcaChallenge { next_challenge },
57        }
58    }
59
60    /// Rejects the payload unless `profile` is [`crate::PROFILE_0_2`].
61    pub fn check_profile(&self) -> Result<(), RejectReason> {
62        check_profile("pic-pca+cose", &self.profile)
63    }
64
65    /// Validates the checkpoint payload before it is signed or accepted.
66    pub fn validate(&self) -> Result<(), RejectReason> {
67        self.check_profile()?;
68        if self.challenge.next_challenge.is_empty() {
69            return Err(RejectReason::NextChallengeInvalid);
70        }
71        self.context_of_authority.validate()
72    }
73}
74
75/// COSE-signed PCA checkpoint.
76pub type PicPcaCose = CoseSigned<PicPcaPayload>;
77
78#[cfg(test)]
79mod tests {
80    use super::*;
81    use crate::authority::{AuthorityValue, Invariant, LogicalAuthority};
82    use std::collections::BTreeMap;
83
84    fn sample_map() -> IndexedAuthorityMap {
85        let mut contract = BTreeMap::new();
86        contract.insert("corporation".into(), AuthorityValue::One("ACME".into()));
87        let logical = LogicalAuthority::new(
88            None,
89            vec![Invariant::new("storage:save", "save", "storage", "*")],
90            contract,
91        );
92        IndexedAuthorityMap::from_logical(&logical).unwrap()
93    }
94
95    #[test]
96    fn pca_cbor_roundtrip() {
97        let pca = PicPcaPayload::new(0, sample_map(), b"challenge-0".to_vec());
98        let mut buf = Vec::new();
99        ciborium::into_writer(&pca, &mut buf).unwrap();
100        let decoded: PicPcaPayload = ciborium::from_reader(buf.as_slice()).unwrap();
101        assert_eq!(pca, decoded);
102        assert!(decoded.check_profile().is_ok());
103    }
104}