hyprstream_rpc/proof/
plan.rs1use anyhow::{bail, Result};
9use ciborium::value::Value as CborValue;
10
11use super::{
12 ALG_ED25519, ALG_ML_DSA_65, MAX_COMPONENTS_PER_GROUP, MAX_KID_BYTES, MAX_SIGNATURE_ENTRIES,
13 MAX_SIGNER_GROUPS, MAX_SIGNER_GROUP_ID, MAX_SUITE_ID_BYTES, SUITE_CLASSICAL, SUITE_HYBRID,
14};
15
16#[derive(Debug, Clone, PartialEq, Eq)]
18pub struct SignatureComponent {
19 pub alg: i64,
21 pub kid: Vec<u8>,
23}
24
25#[derive(Debug, Clone, PartialEq, Eq)]
29pub struct SignerGroup {
30 pub group_id: u64,
32 pub suite_id: String,
34 pub components: Vec<SignatureComponent>,
36}
37
38#[derive(Debug, Clone, PartialEq, Eq)]
42pub struct SignaturePlan {
43 pub groups: Vec<SignerGroup>,
44}
45
46impl SignaturePlan {
47 pub fn decode(v: &CborValue) -> Result<Self> {
50 let arr = match v {
51 CborValue::Array(a) => a,
52 _ => bail!("signature_plan: expected array"),
53 };
54 if arr.is_empty() {
55 bail!("signature_plan: empty plan");
56 }
57 if arr.len() > MAX_SIGNER_GROUPS {
58 bail!(
59 "signature_plan: {} groups exceeds cap of {}",
60 arr.len(),
61 MAX_SIGNER_GROUPS
62 );
63 }
64
65 let mut groups = Vec::with_capacity(arr.len());
66 for elem in arr {
67 groups.push(SignerGroup::decode(elem)?);
68 }
69
70 for w in groups.windows(2) {
72 if w[0].group_id >= w[1].group_id {
73 bail!("signature_plan: group IDs not strictly ascending or not unique");
74 }
75 }
76
77 let mut total = 0usize;
79 let mut seen_pairs = std::collections::HashSet::new();
80 for g in &groups {
81 total += g.components.len();
82 for c in &g.components {
83 let pair = (c.alg, c.kid.clone());
84 if !seen_pairs.insert(pair) {
85 bail!("signature_plan: duplicate (alg, kid) pair across plan");
86 }
87 }
88 }
89 if total > MAX_SIGNATURE_ENTRIES {
90 bail!(
91 "signature_plan: {total} signature entries exceeds cap of {MAX_SIGNATURE_ENTRIES}"
92 );
93 }
94
95 for g in &groups {
97 validate_suite(g)?;
98 }
99
100 Ok(Self { groups })
101 }
102
103 pub fn total_components(&self) -> usize {
105 self.groups.iter().map(|g| g.components.len()).sum()
106 }
107}
108
109impl SignerGroup {
110 fn decode(v: &CborValue) -> Result<Self> {
111 let map = match v {
112 CborValue::Map(m) => m,
113 _ => bail!("signer_group: expected map"),
114 };
115
116 let mut group_id = None;
117 let mut suite_id = None;
118 let mut components = None;
119
120 for (key, val) in map.iter() {
121 let ik = match key {
122 CborValue::Integer(i) => i128::from(*i),
123 _ => bail!("signer_group: non-integer key"),
124 };
125 match ik {
126 1 => {
127 let gid = decode_uint(val, "group_id")?;
128 if gid > MAX_SIGNER_GROUP_ID {
129 bail!("signer_group: group_id {gid} exceeds ceiling {MAX_SIGNER_GROUP_ID}");
130 }
131 group_id = Some(gid);
132 }
133 2 => {
134 suite_id = Some(decode_text(val, "suite_id", MAX_SUITE_ID_BYTES)?);
135 }
136 3 => {
137 components = Some(decode_components(val)?);
138 }
139 _ => bail!("signer_group: unknown key {ik}"),
140 }
141 }
142
143 let group_id = group_id.ok_or_else(|| anyhow::anyhow!("signer_group: missing group_id"))?;
144 let suite_id = suite_id.ok_or_else(|| anyhow::anyhow!("signer_group: missing suite_id"))?;
145 let components =
146 components.ok_or_else(|| anyhow::anyhow!("signer_group: missing components"))?;
147
148 Ok(Self {
149 group_id,
150 suite_id,
151 components,
152 })
153 }
154}
155
156fn decode_components(v: &CborValue) -> Result<Vec<SignatureComponent>> {
157 let arr = match v {
158 CborValue::Array(a) => a,
159 _ => bail!("components: expected array"),
160 };
161 if arr.is_empty() {
162 bail!("components: empty");
163 }
164 if arr.len() > MAX_COMPONENTS_PER_GROUP {
165 bail!(
166 "components: {} exceeds cap of {}",
167 arr.len(),
168 MAX_COMPONENTS_PER_GROUP
169 );
170 }
171
172 let mut out = Vec::with_capacity(arr.len());
173 for elem in arr {
174 let map = match elem {
175 CborValue::Map(m) => m,
176 _ => bail!("signature_component: expected map"),
177 };
178 let mut alg = None;
179 let mut kid = None;
180 for (key, val) in map.iter() {
181 let ik = match key {
182 CborValue::Integer(i) => i128::from(*i),
183 _ => bail!("signature_component: non-integer key"),
184 };
185 match ik {
186 1 => {
187 alg = Some(decode_int(val, "alg")?);
188 }
189 2 => {
190 let k = decode_kid(val)?;
191 if k.is_empty() || k.len() > MAX_KID_BYTES {
192 bail!("kid: must be 1..{MAX_KID_BYTES} bytes, got {}", k.len());
193 }
194 kid = Some(k);
195 }
196 _ => bail!("signature_component: unknown key {ik}"),
197 }
198 }
199 let alg = alg.ok_or_else(|| anyhow::anyhow!("signature_component: missing alg"))?;
200 if alg != ALG_ED25519 && alg != ALG_ML_DSA_65 {
201 bail!("signature_component: alg {alg} not in profile (only {ALG_ED25519} and {ALG_ML_DSA_65})");
202 }
203 let kid = kid.ok_or_else(|| anyhow::anyhow!("signature_component: missing kid"))?;
204 out.push(SignatureComponent { alg, kid });
205 }
206 Ok(out)
207}
208
209fn validate_suite(g: &SignerGroup) -> Result<()> {
211 match g.suite_id.as_str() {
212 s if s == SUITE_CLASSICAL => {
213 if g.components.len() != 1 {
214 bail!(
215 "suite {SUITE_CLASSICAL}: expected exactly 1 component, got {}",
216 g.components.len()
217 );
218 }
219 if g.components[0].alg != ALG_ED25519 {
220 bail!(
221 "suite {SUITE_CLASSICAL}: component alg must be {ALG_ED25519}, got {}",
222 g.components[0].alg
223 );
224 }
225 }
226 s if s == SUITE_HYBRID => {
227 if g.components.len() != 2 {
228 bail!(
229 "suite {SUITE_HYBRID}: expected exactly 2 components, got {}",
230 g.components.len()
231 );
232 }
233 if g.components[0].alg != ALG_ED25519 {
235 bail!("suite {SUITE_HYBRID}: first component must be Ed25519 ({ALG_ED25519})");
236 }
237 if g.components[1].alg != ALG_ML_DSA_65 {
238 bail!("suite {SUITE_HYBRID}: second component must be ML-DSA-65 ({ALG_ML_DSA_65})");
239 }
240 }
241 other => bail!("validate_suite: unknown suite_id '{other}'"),
242 }
243 Ok(())
244}
245
246fn decode_uint(v: &CborValue, name: &str) -> Result<u64> {
247 match v {
248 CborValue::Integer(i) if i128::from(*i) >= 0 => Ok(i128::from(*i) as u64),
249 _ => bail!("{name}: must be non-negative uint"),
250 }
251}
252
253fn decode_int(v: &CborValue, name: &str) -> Result<i64> {
254 match v {
255 CborValue::Integer(i) => Ok(i128::from(*i) as i64),
256 _ => bail!("{name}: must be integer"),
257 }
258}
259
260fn decode_text(v: &CborValue, name: &str, max: usize) -> Result<String> {
261 match v {
262 CborValue::Text(s) => {
263 if s.len() > max {
264 bail!("{name}: exceeds {max} bytes");
265 }
266 Ok(s.clone())
267 }
268 _ => bail!("{name}: must be text"),
269 }
270}
271
272fn decode_kid(v: &CborValue) -> Result<Vec<u8>> {
274 match v {
275 CborValue::Bytes(b) => Ok(b.clone()),
276 _ => bail!("kid: must be bstr"),
277 }
278}