aitp_session_bundle/
builder.rs1use crate::error::SessionBundleError;
7use crate::types::{ParticipantEntry, SessionTrustBundle};
8use aitp_core::{jcs, Aid, Timestamp};
9use aitp_crypto::AitpSigningKey;
10use aitp_tct::TctClaims;
11use serde::Serialize;
12use sha2::{Digest, Sha256};
13use uuid::Uuid;
14
15pub const DEFAULT_BUNDLE_VERSION: &str = "aitp/0.2";
17
18pub(crate) fn peek_tct_claims(token: &str) -> Result<TctClaims, SessionBundleError> {
23 let payload = aitp_crypto::jws::decode_payload_unverified(token)
24 .map_err(|e| SessionBundleError::Canonicalization(format!("participant tct: {e}")))?;
25 serde_json::from_slice(&payload)
26 .map_err(|e| SessionBundleError::Canonicalization(format!("participant tct claims: {e}")))
27}
28
29pub struct SessionBundleBuilder<'a> {
32 coordinator_key: &'a AitpSigningKey,
33 session_id: Option<Uuid>,
34 participants: Vec<ParticipantEntry>,
35 issued_at: Option<Timestamp>,
36}
37
38impl<'a> SessionBundleBuilder<'a> {
39 pub fn new(coordinator_key: &'a AitpSigningKey) -> Self {
41 Self {
42 coordinator_key,
43 session_id: None,
44 participants: Vec::new(),
45 issued_at: None,
46 }
47 }
48
49 pub fn session_id(mut self, id: Uuid) -> Self {
52 self.session_id = Some(id);
53 self
54 }
55
56 pub fn issued_at(mut self, ts: Timestamp) -> Self {
58 self.issued_at = Some(ts);
59 self
60 }
61
62 pub fn participant(mut self, aid: Aid, tct: String) -> Self {
66 self.participants.push(ParticipantEntry { aid, tct });
67 self
68 }
69
70 pub fn build(self) -> Result<SessionTrustBundle, SessionBundleError> {
72 if self.participants.is_empty() {
73 return Err(SessionBundleError::EmptyParticipants);
74 }
75
76 let coordinator = self.coordinator_key.aid().clone();
77 let session_id = self.session_id.unwrap_or_else(Uuid::new_v4);
78 let issued_at = self.issued_at.unwrap_or_else(Timestamp::now);
79
80 let mut min_exp: Option<Timestamp> = None;
85 for entry in &self.participants {
86 let claims = peek_tct_claims(&entry.tct)?;
87 if claims.iss != coordinator {
88 return Err(SessionBundleError::CoordinatorIssuerMismatch);
89 }
90 if claims.aud != entry.aid {
91 return Err(SessionBundleError::AudienceMismatch);
92 }
93 min_exp = Some(match min_exp {
94 Some(m) if m.0 <= claims.exp.0 => m,
95 _ => claims.exp,
96 });
97 }
98
99 let expires_at = min_exp.ok_or(SessionBundleError::EmptyParticipants)?;
101
102 let canonical = bundle_signing_bytes(&BundleSigningBody {
103 version: DEFAULT_BUNDLE_VERSION,
104 session_id: &session_id,
105 coordinator: &coordinator,
106 issued_at: &issued_at,
107 expires_at: &expires_at,
108 participants: &self.participants,
109 })?;
110 let digest = Sha256::digest(&canonical);
111 let signature = self.coordinator_key.sign(&digest);
112
113 Ok(SessionTrustBundle {
114 version: DEFAULT_BUNDLE_VERSION.to_string(),
115 session_id,
116 coordinator,
117 issued_at,
118 expires_at,
119 participants: self.participants,
120 signature: signature.into_string(),
121 })
122 }
123}
124
125pub(crate) fn bundle_signing_bytes(
143 body: &BundleSigningBody<'_>,
144) -> Result<Vec<u8>, SessionBundleError> {
145 jcs::canonicalize_serializable(body)
146 .map_err(|e| SessionBundleError::Canonicalization(e.to_string()))
147}
148
149#[derive(Serialize)]
154pub(crate) struct BundleSigningBody<'a> {
155 pub version: &'a str,
156 pub session_id: &'a Uuid,
157 pub coordinator: &'a Aid,
158 pub issued_at: &'a Timestamp,
159 pub expires_at: &'a Timestamp,
160 pub participants: &'a [ParticipantEntry],
161}
162
163#[cfg(test)]
164mod signing_input_tests {
165 use super::*;
166 use crate::types::SessionTrustBundle;
167
168 #[test]
180 fn production_signing_bytes_match_the_pinned_vector() {
181 let kat_path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
182 .parent()
183 .and_then(|p| p.parent())
184 .expect("repo root")
185 .join("tests/schemas/known-answer/jcs-sha256.json");
186 let kat: serde_json::Value =
187 serde_json::from_slice(&std::fs::read(kat_path).expect("read kat")).unwrap();
188 let v = kat["vectors"]
189 .as_array()
190 .unwrap()
191 .iter()
192 .find(|v| v["id"].as_str() == Some("kat-session-bundle-001"))
193 .expect("kat-session-bundle-001 present");
194
195 let mut obj = v["object"].as_object().expect("object").clone();
199 obj.insert("signature".into(), serde_json::Value::from(""));
200 let bundle: SessionTrustBundle =
201 serde_json::from_value(serde_json::Value::Object(obj)).expect("vector deserializes");
202
203 let canonical = bundle_signing_bytes(&BundleSigningBody {
204 version: &bundle.version,
205 session_id: &bundle.session_id,
206 coordinator: &bundle.coordinator,
207 issued_at: &bundle.issued_at,
208 expires_at: &bundle.expires_at,
209 participants: &bundle.participants,
210 })
211 .expect("canonicalize");
212
213 assert_eq!(
214 canonical.len(),
215 v["jcs_canonical_len_bytes"].as_u64().unwrap() as usize,
216 "production signing bytes diverge in length from kat-session-bundle-001"
217 );
218 assert_eq!(
219 hex::encode(&canonical),
220 v["jcs_canonical_hex"].as_str().unwrap(),
221 "production signing bytes diverge from kat-session-bundle-001 — the \
222 implementation canonicalizes a different shape than the spec signs"
223 );
224 }
225}