Skip to main content

ic_auth_wire/
model.rs

1//! Bounded transport projections. Conversion is structural, never verification.
2use ic_auth_protocol_types as domain;
3use ic_auth_protocol_types::limits::{
4    MAX_CLAIMS_BYTES, MAX_GRANTS, MAX_LABEL_BYTES, MAX_SCOPES_PER_GRANT,
5};
6use ic_wire::{Bytes, Error, List, Text};
7
8trait Field<D>: Sized {
9    fn from_domain(value: D) -> Result<Self, Error>;
10    fn into_domain(self) -> Result<D, Error>;
11}
12macro_rules! scalar {
13    ($($ty:ty),*) => {$(impl Field<$ty> for $ty {
14        fn from_domain(value: $ty) -> Result<Self, Error> { Ok(value) }
15        fn into_domain(self) -> Result<$ty, Error> { Ok(self) }
16    })*};
17}
18scalar!(u16, u64, [u8; 16], [u8; 32], domain::Principal);
19impl<const N: usize> Field<Vec<u8>> for Bytes<N> {
20    fn from_domain(value: Vec<u8>) -> Result<Self, Error> {
21        Self::new(value)
22    }
23    fn into_domain(self) -> Result<Vec<u8>, Error> {
24        Ok(self.into_vec())
25    }
26}
27impl<const N: usize> Field<String> for Text<N> {
28    fn from_domain(value: String) -> Result<Self, Error> {
29        Self::new(value)
30    }
31    fn into_domain(self) -> Result<String, Error> {
32        Ok(self.into_string())
33    }
34}
35impl<D, W: Field<D>, const N: usize> Field<Vec<D>> for List<W, N> {
36    fn from_domain(value: Vec<D>) -> Result<Self, Error> {
37        if value.len() > N {
38            return Err(Error::Limit);
39        }
40        Self::new(
41            value
42                .into_iter()
43                .map(W::from_domain)
44                .collect::<Result<_, _>>()?,
45        )
46    }
47    fn into_domain(self) -> Result<Vec<D>, Error> {
48        self.into_vec().into_iter().map(W::into_domain).collect()
49    }
50}
51impl Field<domain::CanonicalId> for [u8; 32] {
52    fn from_domain(value: domain::CanonicalId) -> Result<Self, Error> {
53        Ok(*value.as_bytes())
54    }
55    fn into_domain(self) -> Result<domain::CanonicalId, Error> {
56        Ok(domain::CanonicalId::from_bytes(self))
57    }
58}
59impl Field<domain::AuthRole> for Text<MAX_LABEL_BYTES> {
60    fn from_domain(value: domain::AuthRole) -> Result<Self, Error> {
61        Self::new(value.into_string())
62    }
63    fn into_domain(self) -> Result<domain::AuthRole, Error> {
64        domain::AuthRole::try_from(self.into_string()).map_err(|_| Error::Malformed)
65    }
66}
67impl Field<domain::ScopeLabel> for Text<MAX_LABEL_BYTES> {
68    fn from_domain(value: domain::ScopeLabel) -> Result<Self, Error> {
69        Self::new(value.into_string())
70    }
71    fn into_domain(self) -> Result<domain::ScopeLabel, Error> {
72        domain::ScopeLabel::try_from(self.into_string()).map_err(|_| Error::Malformed)
73    }
74}
75// One declaration owns each Serde transport field and both typed
76// projections. Rust checks the domain field names/types; no intermediate codec.
77macro_rules! record {
78    ($name:ident { $($field:ident: $ty:ty),* $(,)? }) => {
79        #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
80#[cfg_attr(feature = "typescript", derive(ic_wire::Wire))]
81        #[doc = concat!("Bounded transport projection of [`ic_auth_protocol_types::", stringify!($name), "`]. Conversion checks representation, not proof validity or authority.")]
82        pub struct $name { $(
83            #[doc = concat!("Bounded representation of [`ic_auth_protocol_types::", stringify!($name), "::", stringify!($field), "`]; the domain contract defines its meaning.")]
84            pub $field: $ty
85        ),* }
86        impl TryFrom<domain::$name> for $name {
87            type Error = Error;
88            fn try_from(value: domain::$name) -> Result<Self, Error> {
89                Ok(Self { $($field: Field::from_domain(value.$field)?),* })
90            }
91        }
92        impl TryFrom<$name> for domain::$name {
93            type Error = Error;
94            fn try_from(value: $name) -> Result<Self, Error> {
95                Ok(Self { $($field: Field::into_domain(value.$field)?),* })
96            }
97        }
98        impl Field<domain::$name> for $name {
99            fn from_domain(value: domain::$name) -> Result<Self, Error> { value.try_into() }
100            fn into_domain(self) -> Result<domain::$name, Error> { self.try_into() }
101        }
102    };
103}
104macro_rules! unit_enum {
105    ($name:ident { $($variant:ident),* $(,)? }) => {
106        #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
107#[cfg_attr(feature = "typescript", derive(ic_wire::Wire))]
108        #[doc = concat!("Wire representation of [`ic_auth_protocol_types::", stringify!($name), "`], preserving its domain meanings.")]
109        pub enum $name { $(
110            #[doc = concat!("Transport tag for [`ic_auth_protocol_types::", stringify!($name), "::", stringify!($variant), "`].")]
111            $variant
112        ),* }
113        impl Field<domain::$name> for $name {
114            fn from_domain(value: domain::$name) -> Result<Self, Error> {
115                Ok(value.into())
116            }
117            fn into_domain(self) -> Result<domain::$name, Error> {
118                Ok(self.into())
119            }
120        }
121        impl From<domain::$name> for $name {
122            fn from(value: domain::$name) -> Self {
123                match value { $(domain::$name::$variant => Self::$variant),* }
124            }
125        }
126        impl From<$name> for domain::$name {
127            fn from(value: $name) -> Self {
128                match value { $($name::$variant => Self::$variant),* }
129            }
130        }
131    };
132}
133macro_rules! tuple_enum {
134    ($name:ident { $($variant:ident($ty:ty)),* $(,)? }) => {
135        #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
136#[cfg_attr(feature = "typescript", derive(ic_wire::Wire))]
137        #[doc = concat!("Bounded transport projection of [`ic_auth_protocol_types::", stringify!($name), "`]; decoding does not establish trust.")]
138        pub enum $name { $(
139            #[doc = concat!("Bounded payload for [`ic_auth_protocol_types::", stringify!($name), "::", stringify!($variant), "`].")]
140            $variant($ty)
141        ),* }
142        impl Field<domain::$name> for $name {
143            fn from_domain(value: domain::$name) -> Result<Self, Error> {
144                Ok(match value { $(domain::$name::$variant(v) => Self::$variant(Field::from_domain(v)?)),* })
145            }
146            fn into_domain(self) -> Result<domain::$name, Error> {
147                Ok(match self { $(Self::$variant(v) => domain::$name::$variant(Field::into_domain(v)?)),* })
148            }
149        }
150    };
151}
152record!(AudienceId {
153    canonical_network_id: [u8; 32],
154    fleet_id: [u8; 32]
155});
156record!(DelegatedRoleGrant { target: Text<MAX_LABEL_BYTES>, scopes: List<Text<MAX_LABEL_BYTES>, MAX_SCOPES_PER_GRANT> });
157tuple_enum!(DelegationAudience {
158    Fleet(AudienceId)
159});
160unit_enum!(ChainKeyAlgorithm { EcdsaSecp256k1 });
161record!(ChainKeyKeyId { name: Text<128> });
162unit_enum!(IssuerProofAlgorithm {
163    IcCanisterSignatureV1
164});
165#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
166#[cfg_attr(feature = "typescript", derive(ic_wire::Wire))]
167/// Transport binding for the delegated issuer key, never an independent trust anchor.
168pub enum IssuerProofBinding {
169    /// SHA-256 seed hash required of the issuer's canister-signature public key.
170    IcCanisterSignatureV1([u8; 32]),
171}
172impl Field<domain::IssuerProofBinding> for IssuerProofBinding {
173    fn from_domain(value: domain::IssuerProofBinding) -> Result<Self, Error> {
174        let domain::IssuerProofBinding::IcCanisterSignatureV1 { seed_hash } = value;
175        Ok(Self::IcCanisterSignatureV1(seed_hash))
176    }
177    fn into_domain(self) -> Result<domain::IssuerProofBinding, Error> {
178        let Self::IcCanisterSignatureV1(seed_hash) = self;
179        Ok(domain::IssuerProofBinding::IcCanisterSignatureV1 { seed_hash })
180    }
181}
182record!(IcCanisterSignatureProofV1 { signature_cbor: Bytes<131072>, public_key_der: Bytes<256> });
183record!(ChainKeyBatchHeaderV1 {
184    schema_version: u16,
185    root_canister_id: domain::Principal,
186    batch_id: [u8; 32],
187    proof_epoch: u64,
188    registry_epoch: u64,
189    registry_hash: [u8; 32],
190    tree_root: [u8; 32],
191    not_before_ns: u64,
192    expires_at_ns: u64,
193    algorithm: ChainKeyAlgorithm,
194    key_id: ChainKeyKeyId,
195    derivation_path_hash: [u8; 32],
196    key_version: u64,
197});
198record!(ChainKeyDelegationCertV1 {
199    root_canister_id: domain::Principal, issuer_canister_id: domain::Principal, proof_epoch: u64,
200    issuer_proof_algorithm: IssuerProofAlgorithm, issuer_proof_binding_hash: [u8; 32],
201    issuer_proof_binding: IssuerProofBinding, max_token_ttl_ns: u64,
202    audience: DelegationAudience, grants: List<DelegatedRoleGrant, MAX_GRANTS>,
203    not_before_ns: u64, expires_at_ns: u64, registry_epoch: u64, registry_hash: [u8; 32],
204});
205record!(ChainKeyRootSignatureV1 {
206    algorithm: ChainKeyAlgorithm, key_id: ChainKeyKeyId,
207    derivation_path: List<Bytes<256>, 32>, public_key: Bytes<65>, signature: Bytes<64>,
208});
209tuple_enum!(ChainKeyBatchWitnessStepV1 {
210    LeftSibling([u8; 32]),
211    RightSibling([u8; 32])
212});
213record!(ChainKeyBatchWitnessV1 { steps: List<ChainKeyBatchWitnessStepV1, 64> });
214record!(IcChainKeyBatchSignatureProofV1 {
215    header: ChainKeyBatchHeaderV1,
216    delegation_cert: ChainKeyDelegationCertV1,
217    issuer_witness: ChainKeyBatchWitnessV1,
218    signature: ChainKeyRootSignatureV1,
219});
220tuple_enum!(RootProof {
221    IcChainKeyBatchSignatureV1(IcChainKeyBatchSignatureProofV1)
222});
223record!(DelegationCert {
224    root_pid: domain::Principal, issuer_pid: domain::Principal, issuer_proof_alg: IssuerProofAlgorithm,
225    issuer_proof_binding_hash: [u8; 32], issuer_proof_binding: IssuerProofBinding,
226    issued_at_ns: u64, not_before_ns: u64, expires_at_ns: u64,
227    max_token_ttl_ns: u64, aud: DelegationAudience, grants: List<DelegatedRoleGrant, MAX_GRANTS>,
228});
229record!(DelegationProof {
230    cert: DelegationCert,
231    root_proof: RootProof
232});
233#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
234#[cfg_attr(feature = "typescript", derive(ic_wire::Wire))]
235/// Bounded root delegation and issuer signature for a certified portable credential.
236pub struct CertifiedProof {
237    /// Root authority proof for the issuer's delegated grants.
238    pub delegation: DelegationProof,
239    /// Issuer canister signature covering the canonical claims digest and domain.
240    pub issuer_signature: IcCanisterSignatureProofV1,
241}
242#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
243#[cfg_attr(feature = "typescript", derive(ic_wire::Wire))]
244/// Bounded proof transport; the selected mechanism must match protected enrollment.
245pub enum PortableProof {
246    /// Root-delegated IC canister signature material, still requiring verification.
247    Certified(Box<CertifiedProof>),
248    /// Up to 64 raw signature bytes; strict verification requires exactly 64.
249    Ed25519(Bytes<64>),
250}
251impl Field<domain::PortableProof> for PortableProof {
252    fn from_domain(value: domain::PortableProof) -> Result<Self, Error> {
253        Ok(match value {
254            domain::PortableProof::Certified {
255                delegation,
256                issuer_signature,
257            } => Self::Certified(Box::new(CertifiedProof {
258                delegation: (*delegation).try_into()?,
259                issuer_signature: issuer_signature.try_into()?,
260            })),
261            domain::PortableProof::Ed25519 { signature } => Self::Ed25519(Bytes::new(signature)?),
262        })
263    }
264    fn into_domain(self) -> Result<domain::PortableProof, Error> {
265        Ok(match self {
266            Self::Certified(value) => domain::PortableProof::Certified {
267                delegation: Box::new(value.delegation.try_into()?),
268                issuer_signature: value.issuer_signature.try_into()?,
269            },
270            Self::Ed25519(signature) => domain::PortableProof::Ed25519 {
271                signature: signature.into_vec(),
272            },
273        })
274    }
275}
276record!(PortableCredential { claims: Bytes<MAX_CLAIMS_BYTES>, proof: PortableProof });
277// Admission diagnostics are independent of proof validity and retry policy.
278unit_enum!(AdmissionRefusal {
279    NotYetValid,
280    Expired,
281    InvalidCredential,
282    AuthorityUnavailable,
283    BeforeReset,
284    ScopeRejected,
285    ReplayConflict,
286    Revoked,
287    Capacity,
288    Throttled,
289    Unavailable
290});
291unit_enum!(LogoutUnavailable {
292    Capacity,
293    Storage,
294    Clock,
295    ResetPending
296});
297#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
298#[cfg_attr(feature = "typescript", derive(ic_wire::Wire))]
299/// Local logout response; it never acknowledges revocation at other receivers.
300pub enum LogoutResult {
301    /// Committed denial through the authenticated login deadline in nanoseconds.
302    Revoked(u64),
303    /// Local denial deadline in nanoseconds without confirmation of all outstanding issuance.
304    Unconfirmed(u64),
305    /// The authenticated caller cannot select a logout identity.
306    InvalidCaller,
307    /// Local revocation could not be acknowledged; retain unknown issuance state.
308    Unavailable(LogoutUnavailable),
309}
310impl From<domain::LogoutResult> for LogoutResult {
311    fn from(value: domain::LogoutResult) -> Self {
312        match value {
313            domain::LogoutResult::Revoked { deny_until_ns } => Self::Revoked(deny_until_ns),
314            domain::LogoutResult::Unconfirmed { deny_until_ns } => Self::Unconfirmed(deny_until_ns),
315            domain::LogoutResult::InvalidCaller => Self::InvalidCaller,
316            domain::LogoutResult::Unavailable(reason) => Self::Unavailable(reason.into()),
317        }
318    }
319}
320unit_enum!(SessionReadRefusal {
321    MissingOrExpired,
322    AuthorityUnavailable,
323    ScopeRejected,
324    Revoked,
325    Unavailable
326});