hyprstream_session_store/
primary.rs1use std::collections::BTreeSet;
3use std::time::Duration;
4
5use hyprstream_rpc::auth::det_cbor::{det_cbor, DetCborValue};
6use hyprstream_rpc::auth::signer_suite::signer_suite_thumbprint;
7use sha2::{Digest, Sha256};
8use tokio::sync::Semaphore;
9use tokio_postgres::Client;
10
11use crate::{bounded, Error, Session, Store, PROFILE, SUITE};
12
13pub struct InventorySource {
17 pub id: String,
18 pub keys: Vec<Vec<u8>>,
19}
20
21#[derive(Clone)]
22pub struct CollisionInventory {
23 id: [u8; 32],
24 keys: BTreeSet<Vec<u8>>,
25}
26
27impl CollisionInventory {
28 pub fn from_sources(required: &[String], sources: Vec<InventorySource>) -> Result<Self, Error> {
29 let ids: BTreeSet<_> = required.iter().cloned().collect();
30 if ids.is_empty()
31 || ids.len() != required.len()
32 || ids.len() > 256
33 || ids.iter().any(|id| !bounded(id, 256))
34 || sources.len() != ids.len()
35 {
36 return Err(Error::Invalid);
37 }
38 let mut seen = BTreeSet::new();
39 let mut keys = BTreeSet::new();
40 for source in sources {
41 if !ids.contains(&source.id) || !seen.insert(source.id) || source.keys.len() > 4096 {
42 return Err(Error::Invalid);
43 }
44 for key in source.keys {
45 if !matches!(key.len(), 32 | 1952) {
46 return Err(Error::Invalid);
47 }
48 keys.insert(key);
49 if keys.len() > 4096 {
50 return Err(Error::Invalid);
51 }
52 }
53 }
54 let value = DetCborValue::Array(vec![
55 DetCborValue::Text("hyprstream.session-collision-inventory.v1"),
56 DetCborValue::Array(ids.iter().map(|id| DetCborValue::Text(id)).collect()),
57 DetCborValue::Array(keys.iter().map(|key| DetCborValue::Bytes(key)).collect()),
58 ]);
59 Ok(Self {
60 id: Sha256::digest(det_cbor(&value)).into(),
61 keys,
62 })
63 }
64
65 pub fn id(&self) -> [u8; 32] {
66 self.id
67 }
68
69 pub fn permits(&self, ed: &[u8; 32], pq: &[u8]) -> bool {
70 pq.len() == 1952 && !self.keys.contains(ed.as_slice()) && !self.keys.contains(pq)
71 }
72}
73
74#[derive(Clone, PartialEq, Eq)]
77pub struct ActiveSessionPrimary {
78 pub session: Session,
79 pub created_at: i64,
80}
81
82#[derive(Clone)]
85pub struct ExpectedPrimary {
86 pub issuer: String,
87 pub profile: String,
88 pub sid: String,
89 pub subject: String,
90 pub tenant: String,
91 pub client: String,
92 pub audience: String,
93 pub scopes: Vec<String>,
94 pub ed_public: [u8; 32],
95 pub suite_thumbprint: [u8; 32],
96 pub generation: [u8; 32],
97 pub expires_at: i64,
98}
99
100pub struct LookupCapability {
103 pub service: String,
104 pub service_key: [u8; 32],
105 pub tenant: String,
106 pub resource: String,
107}
108
109pub struct PrimaryLookup {
111 host: String,
112 serving_generation: [u8; 32],
113 inventory: CollisionInventory,
114 capabilities: Vec<LookupCapability>,
115 in_flight: Semaphore,
116}
117
118impl PrimaryLookup {
119 pub fn new(
120 host: String,
121 serving_generation: [u8; 32],
122 inventory: CollisionInventory,
123 capabilities: Vec<LookupCapability>,
124 ) -> Result<Self, Error> {
125 if !bounded(&host, 2048)
126 || capabilities.len() > 256
127 || capabilities.iter().any(|c| {
128 !c.service.starts_with("service:")
129 || !bounded(&c.service, 256)
130 || c.service_key == [0; 32]
131 || !bounded(&c.tenant, 256)
132 || !bounded(&c.resource, 2048)
133 })
134 {
135 return Err(Error::Invalid);
136 }
137 Ok(Self {
138 host,
139 serving_generation,
140 inventory,
141 capabilities,
142 in_flight: Semaphore::new(16),
143 })
144 }
145
146 fn permits(&self, service: &str, service_key: &[u8; 32], tenant: &str, resource: &str) -> bool {
147 self.capabilities.iter().any(|capability| {
148 capability.service == service
149 && &capability.service_key == service_key
150 && (capability.tenant == tenant || capability.tenant == "*")
151 && capability.resource == resource
152 })
153 }
154
155 pub async fn resolve(
158 &self,
159 client: &mut Client,
160 service: &str,
161 service_key: &[u8; 32],
162 expected: &ExpectedPrimary,
163 ) -> Result<ActiveSessionPrimary, Error> {
164 if expected.issuer != self.host
165 || expected.profile != PROFILE
166 || expected.generation != self.serving_generation
167 || !bounded(&expected.sid, 128)
168 || !bounded(&expected.subject, 256)
169 || !bounded(&expected.client, 256)
170 || !bounded(&expected.tenant, 256)
171 || !bounded(&expected.audience, 2048)
172 || expected.scopes.is_empty()
173 || expected.scopes.len() > 64
174 || expected
175 .scopes
176 .iter()
177 .any(|s| !bounded(s, 256) || !s.bytes().all(|b| (0x21..=0x7e).contains(&b)))
178 || expected.scopes.windows(2).any(|s| s[0] >= s[1])
179 || !self.permits(service, service_key, &expected.tenant, &expected.audience)
180 {
181 return Err(Error::Inactive);
182 }
183 let _permit = self
184 .in_flight
185 .try_acquire()
186 .map_err(|_| Error::Unavailable)?;
187 tokio::time::timeout(Duration::from_secs(2), async {
188 let primary = Store::lookup_primary(
191 client,
192 &self.host,
193 &expected.sid,
194 &expected.generation,
195 &self.inventory.id(),
196 )
197 .await?
198 .ok_or(Error::Inactive)?;
199 let active = primary.session();
200 let created_at = primary.created_at();
201 if active.collision_inventory_id != self.inventory.id()
202 || !self.inventory.permits(&active.ed_public, &active.pq_public)
203 || active.subject != expected.subject
204 || active.tenant != expected.tenant
205 || active.client_id != expected.client
206 || active.resource != expected.audience
207 || active.scopes != expected.scopes
208 || active.ed_public != expected.ed_public
209 || signer_suite_thumbprint(SUITE, &[&active.ed_public, &active.pq_public])
210 != expected.suite_thumbprint
211 || expected.expires_at > active.expires_at
212 || expected.expires_at <= created_at
213 {
214 return Err(Error::Inactive);
215 }
216 let now = i64::try_from(
217 std::time::SystemTime::now()
218 .duration_since(std::time::UNIX_EPOCH)
219 .map_err(|_| Error::Unavailable)?
220 .as_secs(),
221 )
222 .map_err(|_| Error::Unavailable)?;
223 if expected.expires_at <= now {
224 return Err(Error::Expired);
225 }
226 Ok(ActiveSessionPrimary {
227 session: active.clone(),
228 created_at,
229 })
230 })
231 .await
232 .map_err(|_| Error::Unavailable)?
233 }
234}
235
236#[cfg(test)]
237mod tests {
238 use super::*;
239
240 #[test]
241 fn complete_inventory_is_order_independent_and_rejects_missing_sources() -> Result<(), Error> {
242 let required = vec!["static:all".into(), "envelope:local".into()];
243 let source = |id: &str, key: u8| InventorySource {
244 id: id.into(),
245 keys: vec![vec![key; 32]],
246 };
247 let a = CollisionInventory::from_sources(
248 &required,
249 vec![source("static:all", 1), source("envelope:local", 2)],
250 )?;
251 let b = CollisionInventory::from_sources(
252 &required,
253 vec![source("envelope:local", 2), source("static:all", 1)],
254 )?;
255 assert_eq!(a.id(), b.id());
256 assert!(!a.permits(&[1; 32], &[3; 1952]));
257 assert!(a.permits(&[3; 32], &[3; 1952]));
258 assert!(
259 CollisionInventory::from_sources(&required, vec![source("static:all", 1)]).is_err()
260 );
261 assert!(CollisionInventory::from_sources(
262 &required,
263 vec![source("static:all", 1), source("static:all", 2)]
264 )
265 .is_err());
266 assert!(CollisionInventory::from_sources(&[], vec![]).is_err());
267 let c = CollisionInventory::from_sources(
268 &required,
269 vec![source("static:all", 3), source("envelope:local", 2)],
270 )?;
271 assert_ne!(a.id(), c.id());
272 Ok(())
273 }
274
275 #[test]
276 fn wildcard_tenant_capability_stays_bound_to_service_key_and_resource() -> Result<(), Error> {
277 let inventory = CollisionInventory::from_sources(
278 &["fixture:static".into()],
279 vec![InventorySource {
280 id: "fixture:static".into(),
281 keys: vec![],
282 }],
283 )?;
284 let lookup = PrimaryLookup::new(
285 "https://host.test".into(),
286 [3; 32],
287 inventory,
288 vec![LookupCapability {
289 service: "service:registry".into(),
290 service_key: [4; 32],
291 tenant: "*".into(),
292 resource: "https://host.test".into(),
293 }],
294 )?;
295 assert!(lookup.permits(
296 "service:registry",
297 &[4; 32],
298 "tenant-a",
299 "https://host.test"
300 ));
301 assert!(!lookup.permits("service:model", &[4; 32], "tenant-a", "https://host.test"));
302 assert!(!lookup.permits(
303 "service:registry",
304 &[5; 32],
305 "tenant-a",
306 "https://host.test"
307 ));
308 assert!(!lookup.permits(
309 "service:registry",
310 &[4; 32],
311 "tenant-a",
312 "https://other.test"
313 ));
314 Ok(())
315 }
316}