1use base64::{engine::general_purpose::URL_SAFE_NO_PAD as B64, Engine};
8use ed25519_dalek::{Signature, VerifyingKey};
9use hyprstream_rpc::crypto::pq::{ml_dsa_verify, ml_dsa_vk_from_bytes};
10use jsonwebtoken::{crypto, Algorithm, DecodingKey};
11use serde::{
12 de::{self, MapAccess, SeqAccess, Visitor},
13 Deserialize, Deserializer,
14};
15use serde_json::Value;
16use sha2::{Digest, Sha256};
17use std::{
18 collections::BTreeMap,
19 fmt,
20 time::{Duration, Instant},
21};
22use subtle::ConstantTimeEq;
23use tokio::sync::Mutex;
24
25pub(crate) const ISSUER: &str = "https://login.federate.to";
26pub(crate) const CLIENT: &str = hyprstream_rpc::auth::claims::FEDERATE_STAGING_CLIENT;
27pub(crate) const TUI_PROFILE: &str = "federate-tui-v1";
31pub(crate) const TUI_DEVICE_PROFILE: &str = "federate-session-v2-device";
37pub(crate) const WEBSITE: &str = "https://www.staging.lab.hyprstream.com";
38pub(crate) const CALLBACK: &str = "https://www.staging.lab.hyprstream.com/federate/callback";
39#[cfg(test)]
40pub(crate) const HOST: &str = hyprstream_rpc::auth::claims::FEDERATE_STAGING_HOST;
41pub(crate) use hyprstream_rpc::auth::claims::FederateHost;
42const JWKS: &str = "https://login.federate.to/keys";
43const SUITE: &str = "hs-cose-sign-ed25519-mldsa65-wns-v1";
44const MAX_JWS: usize = 16 * 1024;
45const MAX_JWKS: usize = 64 * 1024;
46const MAX_TRANSCRIPT: usize = 8 * 1024;
47const MAX_AUTHORITY_TEXT: usize = 256;
48const MAX_SCOPE_BYTES: usize = 1024;
49const KEY_TTL: Duration = Duration::from_secs(60);
50const MAX_CLIENT_TEXT: usize = 256;
51const MAX_CONNECTOR_TEXT: usize = 64;
52
53#[derive(Clone, Debug, PartialEq, Eq)]
66pub(crate) struct ClientClass {
67 client_id: String,
68 aud: String,
69 connector: String,
70}
71
72impl ClientClass {
73 pub(crate) fn staging() -> Self {
75 Self {
76 client_id: CLIENT.into(),
77 aud: CLIENT.into(),
78 connector: "atproto".into(),
79 }
80 }
81
82 pub(crate) fn new(client_id: &str, aud: &str, connector: Option<&str>) -> Result<Self> {
88 let text = |value: &str, max: usize| {
89 require(!value.is_empty() && value.len() <= max)?;
90 require(value.bytes().all(|b| (0x21..=0x7e).contains(&b)))?;
91 Ok(())
92 };
93 text(client_id, MAX_CLIENT_TEXT)?;
94 text(aud, MAX_CLIENT_TEXT)?;
95 let connector = connector.unwrap_or("atproto");
96 text(connector, MAX_CONNECTOR_TEXT)?;
97 require(client_id != CLIENT && aud != CLIENT)?;
98 Ok(Self {
99 client_id: client_id.into(),
100 aud: aud.into(),
101 connector: connector.into(),
102 })
103 }
104
105 pub(crate) fn client_id(&self) -> &str {
106 &self.client_id
107 }
108
109 pub(crate) fn profile(&self) -> &'static str {
113 if self.client_id == CLIENT {
114 "federate-session-v1"
115 } else {
116 TUI_PROFILE
117 }
118 }
119}
120
121#[derive(Debug, PartialEq, Eq, thiserror::Error)]
122pub(crate) enum Error {
123 #[error("Federate verifier disabled")]
124 Disabled,
125 #[error("invalid Federate evidence")]
126 Invalid,
127 #[error("Federate signing authority unavailable")]
128 Unavailable,
129}
130type Result<T> = std::result::Result<T, Error>;
131fn require(ok: bool) -> Result<()> {
132 if ok {
133 Ok(())
134 } else {
135 Err(Error::Invalid)
136 }
137}
138fn sha(bytes: &[u8]) -> [u8; 32] {
139 Sha256::digest(bytes).into()
140}
141fn equal(a: &[u8], b: &[u8]) -> bool {
142 bool::from(a.ct_eq(b))
143}
144fn decode(value: &str, max: usize) -> Result<Vec<u8>> {
145 require(value.len() <= max.saturating_mul(4).div_ceil(3))?;
146 let bytes = B64.decode(value).map_err(|_| Error::Invalid)?;
147 require(bytes.len() <= max && B64.encode(&bytes) == value)?;
148 Ok(bytes)
149}
150fn fixed<const N: usize>(value: &str) -> Result<[u8; N]> {
151 decode(value, N)?.try_into().map_err(|_| Error::Invalid)
152}
153fn text<'a>(value: &'a Value, key: &str) -> Result<&'a str> {
154 let s = value
155 .get(key)
156 .and_then(Value::as_str)
157 .ok_or(Error::Invalid)?;
158 require(!s.is_empty() && s.len() <= 2048)?;
159 Ok(s)
160}
161fn frame(domain: &str, fields: &[&[u8]]) -> Vec<u8> {
162 let mut out = domain.as_bytes().to_vec();
163 out.push(0);
164 out.extend_from_slice(&(fields.len() as u32).to_be_bytes());
165 for field in fields {
166 out.extend_from_slice(&(field.len() as u32).to_be_bytes());
167 out.extend_from_slice(field);
168 }
169 out
170}
171
172struct Unique(Value);
174impl<'de> Deserialize<'de> for Unique {
175 fn deserialize<D: Deserializer<'de>>(d: D) -> std::result::Result<Self, D::Error> {
176 struct V;
177 impl<'de> Visitor<'de> for V {
178 type Value = Unique;
179 fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
180 f.write_str("unique-key JSON")
181 }
182 fn visit_map<M: MapAccess<'de>>(
183 self,
184 mut m: M,
185 ) -> std::result::Result<Unique, M::Error> {
186 let mut out = serde_json::Map::new();
187 while let Some((k, v)) = m.next_entry::<String, Unique>()? {
188 if out.insert(k, v.0).is_some() {
189 return Err(de::Error::custom("duplicate member"));
190 }
191 }
192 Ok(Unique(Value::Object(out)))
193 }
194 fn visit_seq<S: SeqAccess<'de>>(
195 self,
196 mut s: S,
197 ) -> std::result::Result<Unique, S::Error> {
198 let mut out = Vec::new();
199 while let Some(v) = s.next_element::<Unique>()? {
200 out.push(v.0);
201 }
202 Ok(Unique(Value::Array(out)))
203 }
204 fn visit_str<E: de::Error>(self, v: &str) -> std::result::Result<Unique, E> {
205 Ok(Unique(Value::String(v.into())))
206 }
207 fn visit_bool<E: de::Error>(self, v: bool) -> std::result::Result<Unique, E> {
208 Ok(Unique(Value::Bool(v)))
209 }
210 fn visit_u64<E: de::Error>(self, v: u64) -> std::result::Result<Unique, E> {
211 Ok(Unique(v.into()))
212 }
213 fn visit_i64<E: de::Error>(self, v: i64) -> std::result::Result<Unique, E> {
214 Ok(Unique(v.into()))
215 }
216 fn visit_f64<E: de::Error>(self, v: f64) -> std::result::Result<Unique, E> {
217 Ok(Unique(v.into()))
218 }
219 fn visit_unit<E: de::Error>(self) -> std::result::Result<Unique, E> {
220 Ok(Unique(Value::Null))
221 }
222 }
223 d.deserialize_any(V)
224 }
225}
226fn json(bytes: &[u8]) -> Result<Value> {
227 serde_json::from_slice::<Unique>(bytes)
228 .map(|v| v.0)
229 .map_err(|_| Error::Invalid)
230}
231
232pub(crate) struct Commitment {
234 host: FederateHost,
235 client: ClientClass,
239 random: [u8; 32],
240 flow: Flow,
242 ed: [u8; 32],
243 pq: Vec<u8>,
244}
245
246enum Flow {
254 Code { state: String, pkce: String },
255 Device { device_code: String },
256}
257impl Commitment {
258 #[cfg(test)]
259 pub(crate) fn new(random: &str, state: &str, pkce: &str, ed: &str, pq: &str) -> Result<Self> {
260 Self::for_host(
261 FederateHost::new(HOST).map_err(|_| Error::Invalid)?,
262 random,
263 state,
264 pkce,
265 ed,
266 pq,
267 )
268 }
269 pub(crate) fn for_host(
271 host: FederateHost,
272 random: &str,
273 state: &str,
274 pkce: &str,
275 ed: &str,
276 pq: &str,
277 ) -> Result<Self> {
278 Self::for_class(host, &ClientClass::staging(), random, state, pkce, ed, pq)
279 }
280 pub(crate) fn for_class(
282 host: FederateHost,
283 client: &ClientClass,
284 random: &str,
285 state: &str,
286 pkce: &str,
287 ed: &str,
288 pq: &str,
289 ) -> Result<Self> {
290 let (ed, pq) = Self::keys(ed, pq)?;
291 fixed::<32>(state)?;
292 fixed::<32>(pkce)?;
293 Ok(Self {
294 host,
295 client: client.clone(),
296 random: fixed(random)?,
297 flow: Flow::Code {
298 state: state.into(),
299 pkce: pkce.into(),
300 },
301 ed,
302 pq,
303 })
304 }
305 pub(crate) fn for_class_device(
309 host: FederateHost,
310 client: &ClientClass,
311 random: &str,
312 device_code: &str,
313 ed: &str,
314 pq: &str,
315 ) -> Result<Self> {
316 let (ed, pq) = Self::keys(ed, pq)?;
317 require(
318 !device_code.is_empty()
319 && device_code.len() <= MAX_AUTHORITY_TEXT
320 && device_code.is_ascii(),
321 )?;
322 Ok(Self {
323 host,
324 client: client.clone(),
325 random: fixed(random)?,
326 flow: Flow::Device {
327 device_code: device_code.into(),
328 },
329 ed,
330 pq,
331 })
332 }
333 fn keys(ed: &str, pq: &str) -> Result<([u8; 32], Vec<u8>)> {
334 let ed = fixed(ed)?;
335 let vk = VerifyingKey::from_bytes(&ed).map_err(|_| Error::Invalid)?;
336 require(!vk.is_weak())?;
337 let pq = decode(pq, 1952)?;
338 ml_dsa_vk_from_bytes(&pq).map_err(|_| Error::Invalid)?;
339 Ok((ed, pq))
340 }
341 fn preimage(&self) -> Vec<u8> {
342 match &self.flow {
343 Flow::Code { state, pkce } => frame(
344 "hyprstream.federate.session-primary.nonce.v1",
345 &[
346 ISSUER.as_bytes(),
347 self.client.client_id.as_bytes(),
348 WEBSITE.as_bytes(),
349 CALLBACK.as_bytes(),
350 self.host.as_str().as_bytes(),
351 self.host.as_str().as_bytes(),
352 &self.random,
353 &self.ed,
354 &self.pq,
355 &sha(state.as_bytes()),
356 pkce.as_bytes(),
357 ],
358 ),
359 Flow::Device { device_code } => frame(
363 "hyprstream.federate.session-primary.device-nonce.v1",
364 &[
365 &self.random,
366 device_code.as_bytes(),
367 self.client.client_id.as_bytes(),
368 &self.ed,
369 &self.pq,
370 ],
371 ),
372 }
373 }
374 pub(crate) fn nonce(&self) -> String {
375 format!("hsn1.{}", B64.encode(sha(&self.preimage())))
376 }
377 fn kids(&self) -> [[u8; 32]; 2] {
378 session_primary_kids(&self.ed, &self.pq)
379 }
380}
381
382pub(super) fn session_primary_kids(ed: &[u8; 32], pq: &[u8]) -> [[u8; 32]; 2] {
384 [
385 sha(&frame(
386 "hyprstream.session-primary.kid.v1",
387 &[b"Ed25519", ed],
388 )),
389 sha(&frame(
390 "hyprstream.session-primary.kid.v1",
391 &[b"ML-DSA-65", pq],
392 )),
393 ]
394}
395
396struct Keys {
397 fetched: Instant,
398 keys: BTreeMap<String, DecodingKey>,
399}
400fn parse_keys(bytes: &[u8]) -> Result<BTreeMap<String, DecodingKey>> {
401 require(bytes.len() <= MAX_JWKS)?;
402 let doc = json(bytes)?;
403 let entries = doc
404 .get("keys")
405 .and_then(Value::as_array)
406 .ok_or(Error::Invalid)?;
407 require(!entries.is_empty() && entries.len() <= 16)?;
408 let mut keys = BTreeMap::new();
409 for entry in entries {
410 let obj = entry.as_object().ok_or(Error::Invalid)?;
411 require(
412 obj.keys()
413 .all(|k| ["kid", "kty", "use", "alg", "n", "e", "key_ops"].contains(&k.as_str())),
414 )?;
415 require(text(entry, "kty")? == "RSA")?;
416 for (k, expected) in [("alg", "RS256"), ("use", "sig")] {
417 if let Some(v) = entry.get(k) {
418 require(v.as_str() == Some(expected))?;
419 }
420 }
421 if let Some(ops) = entry.get("key_ops") {
422 require(*ops == serde_json::json!(["verify"]))?;
423 }
424 let n = text(entry, "n")?;
425 let e = text(entry, "e")?;
426 let modulus = decode(n, 512)?;
427 require(
428 (256..=512).contains(&modulus.len())
429 && modulus[0] >= 128
430 && modulus.last().is_some_and(|b| b & 1 == 1),
431 )?;
432 let exponent = decode(e, 4)?;
433 require(!exponent.is_empty() && exponent[0] != 0)?;
434 let exponent = exponent.iter().fold(0u64, |n, b| (n << 8) | u64::from(*b));
435 require(exponent >= 3 && exponent % 2 == 1)?;
436 let key = DecodingKey::from_rsa_components(n, e).map_err(|_| Error::Invalid)?;
437 require(keys.insert(text(entry, "kid")?.into(), key).is_none())?;
438 }
439 Ok(keys)
440}
441
442#[derive(Default)]
444pub(crate) struct Verifier {
445 host: Option<FederateHost>,
446 tui_client: Option<ClientClass>,
450 client: Option<reqwest::Client>,
451 keys: Mutex<Option<Keys>>,
452 #[cfg(test)]
453 responses: Option<parking_lot::Mutex<Vec<Result<Vec<u8>>>>>,
454}
455
456#[cfg(test)]
457impl Verifier {
458 pub(crate) fn set_test_responses(&mut self, responses: Vec<Result<Vec<u8>>>) {
460 self.responses = Some(parking_lot::Mutex::new(responses));
461 }
462}
463impl Verifier {
464 #[cfg(test)]
465 pub(crate) fn fixed_staging() -> Result<Self> {
466 Self::for_host(FederateHost::new(HOST).map_err(|_| Error::Invalid)?)
467 }
468 pub(crate) fn host(&self) -> Result<&FederateHost> {
469 self.host.as_ref().ok_or(Error::Disabled)
470 }
471 pub(crate) fn for_host(host: FederateHost) -> Result<Self> {
472 let client = reqwest::Client::builder()
473 .redirect(reqwest::redirect::Policy::none())
474 .timeout(Duration::from_secs(2))
475 .build()
476 .map_err(|_| Error::Unavailable)?;
477 Ok(Self {
478 host: Some(host),
479 tui_client: None,
480 client: Some(client),
481 keys: Mutex::new(None),
482 #[cfg(test)]
483 responses: None,
484 })
485 }
486 pub(crate) fn with_client_class(mut self, class: ClientClass) -> Self {
489 self.tui_client = Some(class);
490 self
491 }
492 pub(crate) fn resolve_client_class(&self, client_id: &str) -> Result<ClientClass> {
496 if client_id == CLIENT {
497 return Ok(ClientClass::staging());
498 }
499 match &self.tui_client {
500 Some(class) if class.client_id == client_id => Ok(class.clone()),
501 _ => Err(Error::Invalid),
502 }
503 }
504
505 pub(crate) fn tui_client(&self) -> Option<&ClientClass> {
508 self.tui_client.as_ref()
509 }
510
511 pub(crate) fn tui_client_id(&self) -> Option<&str> {
514 self.tui_client
515 .as_ref()
516 .map(|class| class.client_id.as_str())
517 }
518 async fn fetch(&self, client: &reqwest::Client) -> Result<Vec<u8>> {
519 #[cfg(test)]
520 if let Some(responses) = &self.responses {
521 let mut responses = responses.lock();
522 return if responses.is_empty() {
523 Err(Error::Unavailable)
524 } else {
525 responses.remove(0)
526 };
527 }
528 let mut response = client
529 .get(JWKS)
530 .send()
531 .await
532 .map_err(|_| Error::Unavailable)?;
533 if !response.status().is_success()
534 || response
535 .content_length()
536 .is_some_and(|n| n > MAX_JWKS as u64)
537 {
538 return Err(Error::Unavailable);
539 }
540 let mut bytes = Vec::new();
541 while let Some(chunk) = response.chunk().await.map_err(|_| Error::Unavailable)? {
542 if bytes.len() + chunk.len() > MAX_JWKS {
543 return Err(Error::Unavailable);
544 }
545 bytes.extend_from_slice(&chunk);
546 }
547 Ok(bytes)
548 }
549 async fn key(&self, kid: &str) -> Result<DecodingKey> {
550 let client = self.client.as_ref().ok_or(Error::Disabled)?;
551 tokio::time::timeout(Duration::from_secs(2), async {
553 let mut cache = self.keys.lock().await;
554 if let Some(keys) = cache.as_ref().filter(|k| k.fetched.elapsed() < KEY_TTL) {
555 if let Some(key) = keys.keys.get(kid) {
556 return Ok(key.clone());
557 }
558 }
559 let bytes = self.fetch(client).await?;
561 let keys = parse_keys(&bytes).map_err(|_| Error::Unavailable)?;
562 let key = keys.get(kid).cloned().ok_or(Error::Invalid);
563 *cache = Some(Keys {
564 fetched: Instant::now(),
565 keys,
566 });
567 key
568 })
569 .await
570 .map_err(|_| Error::Unavailable)?
571 }
572 pub(crate) async fn source(
573 &self,
574 token: &str,
575 code: &str,
576 commitment: Commitment,
577 now: u64,
578 access_token: Option<&str>,
579 ) -> Result<Source> {
580 require(self.host()? == &commitment.host)?;
581 require(
588 self.resolve_client_class(commitment.client.client_id.as_str())? == commitment.client,
589 )?;
590 require(token.len() <= MAX_JWS && !token.is_empty())?;
591 let parts: Vec<_> = token.split('.').collect();
592 require(parts.len() == 3)?;
593 let header = json(&decode(parts[0], 2048)?)?;
594 require(
595 header
596 .as_object()
597 .ok_or(Error::Invalid)?
598 .keys()
599 .all(|k| ["alg", "kid", "typ"].contains(&k.as_str())),
600 )?;
601 require(text(&header, "alg")? == "RS256")?;
602 if let Some(typ) = header.get("typ") {
603 require(typ.as_str() == Some("JWT"))?;
604 }
605 let claims = json(&decode(parts[1], MAX_JWS)?)?;
606 let sig = decode(parts[2], 512)?;
607 require((256..=512).contains(&sig.len()))?;
608 let key = self.key(text(&header, "kid")?).await?;
609 let signed = &token[..token.len() - parts[2].len() - 1];
610 require(
611 crypto::verify(parts[2], signed.as_bytes(), &key, Algorithm::RS256)
612 .map_err(|_| Error::Invalid)?,
613 )?;
614 validate_claims(&claims, code, &commitment, now, access_token)?;
615 Ok(Source {
616 subject: text(&claims, "sub")?.into(),
617 atproto_did: atproto_account_did(&claims, &commitment.client.connector)?,
618 jti: text(&claims, "jti")?.into(),
619 issued_at: number(&claims, "iat")?,
620 expires_at: number(&claims, "exp")?,
621 token_hash: sha(token.as_bytes()),
622 code_hash: sha(code.as_bytes()),
623 commitment,
624 })
625 }
626}
627fn number(v: &Value, k: &str) -> Result<u64> {
628 v.get(k).and_then(Value::as_u64).ok_or(Error::Invalid)
629}
630fn times(iat: u64, exp: u64, now: u64) -> Result<()> {
631 require(
632 exp <= i64::MAX as u64
633 && exp > iat
634 && exp - iat <= 300
635 && iat <= now.saturating_add(30)
636 && now.saturating_sub(iat) <= 120
637 && now < exp,
638 )
639}
640fn hash_claim(claim: &str, input: &str) -> Result<()> {
641 require(!input.is_empty() && input.len() <= MAX_JWS && input.is_ascii())?;
642 require(equal(&fixed::<16>(claim)?, &sha(input.as_bytes())[..16]))
643}
644
645pub(super) fn atproto_account_did(
646 v: &Value,
647 connector: &str,
648) -> std::result::Result<String, Error> {
649 let claims = v
650 .get("federated_claims")
651 .and_then(Value::as_object)
652 .ok_or(Error::Invalid)?;
653 require(claims.get("connector_id").and_then(Value::as_str) == Some(connector))?;
654 let did = claims
655 .get("user_id")
656 .and_then(Value::as_str)
657 .ok_or(Error::Invalid)?;
658 require(did.len() <= 255 && did.is_ascii())?;
659 let method_specific = did.strip_prefix("did:").ok_or(Error::Invalid)?;
662 let (method, specific) = method_specific.split_once(':').ok_or(Error::Invalid)?;
663 match method {
664 "plc" => {
665 require(
666 specific.len() == 24
667 && specific
668 .bytes()
669 .all(|b| b.is_ascii_lowercase() || (b'2'..=b'7').contains(&b)),
670 )?;
671 }
672 "web" => {
673 require(!hyprstream_pds::repo_authority::is_path_form_did_web(did))?;
678 require(
679 !specific.is_empty()
680 && specific.split(':').all(|part| !part.is_empty())
681 && specific.bytes().all(|b| {
682 b.is_ascii_alphanumeric()
683 || b == b'.'
684 || b == b'-'
685 || b == b'%'
686 || b == b':'
687 }),
688 )?;
689 let bytes = specific.as_bytes();
690 for (i, byte) in bytes.iter().enumerate() {
691 if *byte == b'%' {
692 require(
693 i + 2 < bytes.len()
694 && bytes[i + 1].is_ascii_hexdigit()
695 && bytes[i + 2].is_ascii_hexdigit(),
696 )?;
697 }
698 }
699 }
700 _ => return Err(Error::Invalid),
701 }
702 Ok(did.to_owned())
703}
704
705fn validate_claims(
706 v: &Value,
707 code: &str,
708 c: &Commitment,
709 now: u64,
710 access: Option<&str>,
711) -> Result<()> {
712 let class = &c.client;
715 require(text(v, "iss")? == ISSUER)?;
716 require(v.get("aud").is_some_and(|a| {
717 a.as_str() == Some(class.aud.as_str()) || *a == serde_json::json!([class.aud.as_str()])
718 }))?;
719 match v.get("azp") {
724 Some(azp) => require(azp.as_str() == Some(class.client_id.as_str()))?,
725 None => require(class.aud == class.client_id)?,
726 }
727 text(v, "sub")?;
728 atproto_account_did(v, &class.connector)?;
729 text(v, "jti")?;
730 let iat = number(v, "iat")?;
731 let exp = number(v, "exp")?;
732 times(iat, exp, now)?;
733 if v.get("nbf").is_some() {
734 let n = number(v, "nbf")?;
735 require(n <= now.saturating_add(30) && n <= exp)?;
736 }
737 match &c.flow {
738 Flow::Code { .. } => {
739 require(equal(text(v, "nonce")?.as_bytes(), c.nonce().as_bytes()))?;
740 hash_claim(text(v, "c_hash")?, code)?;
741 }
742 Flow::Device { .. } => {
750 require(text(v, "binding_key")? == B64.encode(c.ed))?;
751 }
752 }
753 if v.get("at_hash").is_some() {
754 let claim = text(v, "at_hash")?;
755 fixed::<16>(claim)?;
756 if let Some(access) = access {
757 hash_claim(claim, access)?;
758 }
759 }
760 Ok(())
761}
762
763pub(crate) struct Source {
765 subject: String,
766 atproto_did: String,
767 jti: String,
768 issued_at: u64,
769 expires_at: u64,
770 token_hash: [u8; 32],
771 code_hash: [u8; 32],
772 commitment: Commitment,
773}
774impl Source {
775 pub(crate) fn provenance(&self) -> (&str, &str) {
779 (ISSUER, &self.subject)
780 }
781
782 #[allow(dead_code)] pub(crate) fn proof_public_keys(&self) -> (&[u8; 32], &[u8]) {
786 (&self.commitment.ed, &self.commitment.pq)
787 }
788
789 pub(crate) fn client_id(&self) -> &str {
795 self.commitment.client.client_id.as_str()
796 }
797
798 #[cfg(feature = "postgres")]
804 pub(crate) fn is_device_flow(&self) -> bool {
805 matches!(self.commitment.flow, Flow::Device { .. })
806 }
807
808 #[cfg(feature = "postgres")]
809 pub(crate) fn store_source(&self) -> hyprstream_session_store::Source {
810 hyprstream_session_store::Source {
811 issuer: ISSUER.into(),
812 subject: self.subject.clone(),
813 atproto_did: self.atproto_did.clone(),
814 jti: self.jti.clone(),
815 nonce: self.commitment.nonce(),
816 token_hash: self.token_hash,
817 issued_at: self.issued_at as i64,
818 expires_at: self.expires_at as i64,
819 }
820 }
821}
822#[derive(Clone)]
824pub(crate) struct AuthorityBinding {
825 pub account: String,
826 pub subject: String,
827 pub tenant: String,
828 pub requested: String,
829 pub granted: String,
830 pub revision: String,
831}
832pub(crate) fn scopes(s: &str) -> Result<()> {
833 require(!s.is_empty() && s.len() <= MAX_SCOPE_BYTES)?;
836 let mut previous = "";
837 for token in s.split(' ') {
838 require(
839 !token.is_empty()
840 && token
841 .bytes()
842 .all(|b| b == 0x21 || (0x23..=0x5b).contains(&b) || (0x5d..=0x7e).contains(&b))
843 && token > previous,
844 )?;
845 previous = token;
846 }
847 Ok(())
848}
849fn authority_text(s: &str) -> Result<()> {
850 require(
851 !s.is_empty()
852 && s.len() <= MAX_AUTHORITY_TEXT
853 && !s.bytes().any(|b| b <= 0x1f || b == 0x7f),
854 )
855}
856pub(crate) struct Challenge {
857 source: Source,
858 binding: AuthorityBinding,
859 id: [u8; 32],
860 created: u64,
861 expires: u64,
862 transcript: Vec<u8>,
863}
864impl Source {
865 pub(crate) fn challenge(
866 self,
867 binding: AuthorityBinding,
868 id: [u8; 32],
869 created: u64,
870 ) -> Result<Challenge> {
871 times(self.issued_at, self.expires_at, created)?;
872 for s in [
873 &binding.account,
874 &binding.subject,
875 &binding.tenant,
876 &binding.revision,
877 ] {
878 authority_text(s)?;
879 }
880 require(binding.tenant != "*")?;
881 scopes(&binding.requested)?;
882 scopes(&binding.granted)?;
883 require(
884 binding
885 .granted
886 .split(' ')
887 .all(|s| binding.requested.split(' ').any(|r| r == s)),
888 )?;
889 let expires = created
890 .saturating_add(60)
891 .min(self.expires_at)
892 .min(self.issued_at.saturating_add(120));
893 require(expires > created)?;
894 let kids = self.commitment.kids();
895 let transcript = frame(
896 "hyprstream.session-primary.possession.v1",
897 &[
898 self.commitment.host.as_str().as_bytes(),
899 self.commitment.host.token_endpoint().as_bytes(),
900 ISSUER.as_bytes(),
901 self.commitment.client.client_id.as_bytes(),
902 WEBSITE.as_bytes(),
903 &id,
904 &self.token_hash,
905 self.commitment.nonce().as_bytes(),
906 &self.code_hash,
907 &sha(&self.commitment.preimage()),
908 binding.account.as_bytes(),
909 binding.subject.as_bytes(),
910 binding.tenant.as_bytes(),
911 self.commitment.host.as_str().as_bytes(),
912 binding.requested.as_bytes(),
913 binding.granted.as_bytes(),
914 &created.to_be_bytes(),
915 &expires.to_be_bytes(),
916 SUITE.as_bytes(),
917 &kids[0],
918 &kids[1],
919 binding.revision.as_bytes(),
920 ],
921 );
922 require(transcript.len() <= MAX_TRANSCRIPT)?;
926 Ok(Challenge {
927 source: self,
928 binding,
929 id,
930 created,
931 expires,
932 transcript,
933 })
934 }
935}
936pub(crate) struct VerifiedPossession {
938 source: Source,
939 binding: AuthorityBinding,
940 challenge_id: [u8; 32],
941 created_at: u64,
942 expires_at: u64,
943}
944impl Challenge {
945 pub(crate) fn transcript(&self) -> &[u8] {
946 &self.transcript
947 }
948 pub(crate) fn expires_at(&self) -> u64 {
949 self.expires
950 }
951 pub(crate) fn challenge_id(&self) -> [u8; 32] {
952 self.id
953 }
954 pub(crate) fn granted_scope(&self) -> &str {
955 &self.binding.granted
956 }
957 pub(crate) fn expected_session(&self) -> (AuthorityBinding, [u8; 32], Vec<u8>) {
958 (
959 self.binding.clone(),
960 self.source.commitment.ed,
961 self.source.commitment.pq.clone(),
962 )
963 }
964 pub(crate) fn verify(
965 self,
966 source: Source,
967 id: &[u8; 32],
968 ed_sig: &[u8],
969 pq_sig: &[u8],
970 now: u64,
971 ) -> Result<VerifiedPossession> {
972 require(
973 now >= self.created
974 && now < self.expires
975 && equal(id, &self.id)
976 && equal(&source.token_hash, &self.source.token_hash)
977 && equal(&source.code_hash, &self.source.code_hash)
978 && equal(
979 &source.commitment.preimage(),
980 &self.source.commitment.preimage(),
981 ),
982 )?;
983 times(source.issued_at, source.expires_at, now)?;
984 require(ed_sig.len() == 64 && pq_sig.len() == 3309)?;
985 let c = &source.commitment;
986 let vk = VerifyingKey::from_bytes(&c.ed).map_err(|_| Error::Invalid)?;
987 vk.verify_strict(
988 &self.transcript,
989 &Signature::from_slice(ed_sig).map_err(|_| Error::Invalid)?,
990 )
991 .map_err(|_| Error::Invalid)?;
992 ml_dsa_verify(
993 &ml_dsa_vk_from_bytes(&c.pq).map_err(|_| Error::Invalid)?,
994 &self.transcript,
995 pq_sig,
996 )
997 .map_err(|_| Error::Invalid)?;
998 Ok(VerifiedPossession {
999 source,
1000 binding: self.binding,
1001 challenge_id: self.id,
1002 created_at: self.created,
1003 expires_at: self.expires,
1004 })
1005 }
1006}
1007
1008impl VerifiedPossession {
1009 #[cfg(feature = "postgres")]
1013 pub(crate) fn client_id(&self) -> &str {
1014 self.source.commitment.client.client_id.as_str()
1015 }
1016
1017 #[cfg(feature = "postgres")]
1022 pub(crate) fn into_admission_parts(
1023 self,
1024 ) -> (
1025 hyprstream_session_store::Source,
1026 [u8; 32],
1027 Vec<u8>,
1028 AuthorityBinding,
1029 [u8; 32],
1030 u64,
1031 u64,
1032 bool,
1033 ) {
1034 let device_flow = self.source.is_device_flow();
1035 let source = self.source.store_source();
1036 (
1037 source,
1038 self.source.commitment.ed,
1039 self.source.commitment.pq,
1040 self.binding,
1041 self.challenge_id,
1042 self.created_at,
1043 self.expires_at,
1044 device_flow,
1045 )
1046 }
1047}
1048
1049#[cfg(test)]
1050mod tests;