1use ed25519_dalek::{Signature, VerifyingKey};
4use prost::Message;
5use sha2::{Digest, Sha256};
6
7#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
8pub enum Reject {
9 #[error("unsupported format")]
10 Version,
11 #[error("noncanonical or missing field")]
12 Canonical,
13 #[error("size or count bound exceeded")]
14 Bounds,
15 #[error("invalid signature")]
16 Signature,
17 #[error("independent authority/root mismatch")]
18 Root,
19 #[error("semantically invalid record")]
20 Semantic,
21 #[error("generation rollback or equivocation")]
22 HighWater,
23 #[error("illegal signer lifecycle transition")]
24 Transition,
25 #[error("job key cannot be a witness")]
26 JobAsWitness,
27 #[error("key roles overlap")]
28 KeyRole,
29 #[error("authority is not valid at verification time")]
30 Expired,
31 #[error("delegation scope violation")]
32 Scope,
33 #[error("prepared frozen fields changed")]
34 PreparedFields,
35 #[error("preparation refused: {0:?}")]
36 PreparationRefused(crate::heddle::api::v1alpha2::ImportPreparationRefusalReason),
37 #[error("observe mode lacks its signed disclosure")]
38 RefDisclosure,
39 #[error("known commit must be pinned exactly")]
40 RefPinning,
41 #[error("missing or mismatched provider source selection")]
42 SourceSelection,
43 #[error("ImportSource requires CommitImportJob")]
44 ImportSourceRequiresCommit,
45 #[error("client operation ID was reused with changed inputs")]
46 OperationIdReused,
47 #[error("Commit must return its created pending operation")]
48 PendingOperation,
49 #[error("delegation window exceeds prepared host bounds")]
50 ValidityBounds,
51 #[error("genesis binding does not match prepared branch")]
52 GenesisBinding,
53 #[error("missing typed owner import permission")]
54 ImportPermission,
55 #[error("referenced publication manifest is missing")]
56 StaleManifest,
57 #[error("publication includes an already committed slot")]
58 CommittedSlot,
59 #[error("context is stale at mutation boundary")]
60 StaleContext,
61 #[error("missing or invalid exact retirement inclusion proof")]
62 Proof,
63 #[error("witness is revoked")]
64 Revoked,
65 #[error("committed slot conflict")]
66 SlotConflict,
67 #[error("missing or mismatched exact boundary acceptance binding")]
68 BoundaryAcceptance,
69 #[error("incompatible peer")]
70 Protocol,
71}
72
73pub trait Canonical {
74 fn write(&self, out: &mut Vec<u8>) -> Result<(), Reject>;
75}
76pub fn canonical<T: Canonical>(value: &T) -> Result<Vec<u8>, Reject> {
77 let mut out = Vec::new();
78 value.write(&mut out)?;
79 if out.len() > 1024 * 1024 {
80 return Err(Reject::Bounds);
81 }
82 Ok(out)
83}
84pub fn counted(out: &mut Vec<u8>, value: &[u8]) -> Result<(), Reject> {
85 if value.len() > 1024 * 1024
86 || out.len().saturating_add(value.len()).saturating_add(4) > 1024 * 1024
87 {
88 return Err(Reject::Bounds);
89 }
90 out.extend_from_slice(&(value.len() as u32).to_be_bytes());
91 out.extend_from_slice(value);
92 Ok(())
93}
94pub fn hash(parts: &[&[u8]]) -> Vec<u8> {
95 let mut hash = Sha256::new();
96 for part in parts {
97 hash.update(part);
98 }
99 hash.finalize().to_vec()
100}
101pub fn signing_digest<T: Canonical>(domain: &str, value: &T) -> Result<Vec<u8>, Reject> {
102 Ok(hash(&[domain.as_bytes(), &canonical(value)?]))
103}
104pub fn key_id(public_key: &[u8]) -> Vec<u8> {
105 hash(&[b"heddle-key-v1", &1_u32.to_be_bytes(), public_key])
106}
107pub fn width(value: &[u8], expected: usize) -> Result<(), Reject> {
108 if value.len() != expected {
109 return Err(Reject::Canonical);
110 }
111 Ok(())
112}
113pub fn verify(public_key: &[u8], input: &[u8], signature: &[u8]) -> Result<(), Reject> {
114 let key: &[u8; 32] = public_key.try_into().map_err(|_| Reject::Canonical)?;
115 let signature: &[u8; 64] = signature.try_into().map_err(|_| Reject::Canonical)?;
116 VerifyingKey::from_bytes(key)
117 .map_err(|_| Reject::Signature)?
118 .verify_strict(input, &Signature::from_bytes(signature))
119 .map_err(|_| Reject::Signature)
120}
121pub fn strict_decode<T: Message + Default>(bytes: &[u8], max: usize) -> Result<T, Reject> {
125 if bytes.is_empty() || bytes.len() > max {
126 return Err(Reject::Bounds);
127 }
128 let value = T::decode(bytes).map_err(|_| Reject::Canonical)?;
129 if value.encode_to_vec() != bytes {
130 return Err(Reject::Canonical);
131 }
132 Ok(value)
133}
134
135macro_rules! field {
136 ($out:ident, $v:expr, b) => {
137 $crate::hybrid_codec::counted($out, &$v)?
138 };
139 ($out:ident, $v:expr, s) => {
140 $crate::hybrid_codec::counted($out, $v.as_bytes())?
141 };
142 ($out:ident, $v:expr, u) => {
143 $out.extend_from_slice(&$v.to_be_bytes())
144 };
145 ($out:ident, $v:expr, e) => {
146 $out.extend_from_slice(
147 &u32::try_from($v)
148 .map_err(|_| $crate::hybrid_codec::Reject::Canonical)?
149 .to_be_bytes(),
150 )
151 };
152 ($out:ident, $v:expr, m) => {
153 $crate::hybrid_codec::Canonical::write(
154 $v.as_ref().ok_or($crate::hybrid_codec::Reject::Canonical)?,
155 $out,
156 )?
157 };
158 ($out:ident, $v:expr, o) => {
159 $out.extend_from_slice(&u32::from($v.is_some()).to_be_bytes());
160 if let Some(value) = &$v {
161 $crate::hybrid_codec::Canonical::write(value, $out)?;
162 }
163 };
164 ($out:ident, $v:expr, l) => {
165 if $v.len() > 4096 {
166 return Err($crate::hybrid_codec::Reject::Bounds);
167 }
168 $out.extend_from_slice(&($v.len() as u32).to_be_bytes());
169 for value in &$v {
170 $crate::hybrid_codec::Canonical::write(value, $out)?;
171 }
172 };
173 ($out:ident, $v:expr, p) => {
174 if $v.len() > 4 {
175 return Err($crate::hybrid_codec::Reject::Bounds);
176 }
177 $out.extend_from_slice(&($v.len() as u32).to_be_bytes());
178 for value in &$v {
179 $out.extend_from_slice(
180 &u32::try_from(*value)
181 .map_err(|_| $crate::hybrid_codec::Reject::Canonical)?
182 .to_be_bytes(),
183 );
184 }
185 };
186 ($out:ident, $v:expr, h) => {
187 if $v.len() > 128 {
188 return Err($crate::hybrid_codec::Reject::Bounds);
189 }
190 $out.extend_from_slice(&($v.len() as u32).to_be_bytes());
191 for value in &$v {
192 $crate::hybrid_codec::counted($out, value)?;
193 }
194 };
195 ($out:ident, $v:expr, q) => {
196 if $v.len() > 64 {
197 return Err($crate::hybrid_codec::Reject::Bounds);
198 }
199 $out.extend_from_slice(&($v.len() as u32).to_be_bytes());
200 for value in &$v {
201 $crate::hybrid_codec::counted($out, value)?;
202 }
203 };
204}
205macro_rules! record {
206 ($ty:ty, $($field:ident : $kind:ident),+ $(,)?) => {
207 impl $crate::hybrid_codec::Canonical for $ty {
208 fn write(&self, out: &mut Vec<u8>) -> Result<(), $crate::hybrid_codec::Reject> {
209 $(field!(out, self.$field, $kind);
210 if out.len() > 1024 * 1024 { return Err($crate::hybrid_codec::Reject::Bounds); })+
211 Ok(())
212 }
213 }
214 };
215}
216pub(crate) use {field, record};