Skip to main content

hyprstream_session_store/
lib.rs

1//! Source-only internal persistence foundation. No network listener, token signer,
2//! runtime factory, migration-on-start or account authority is installed here.
3//! Policy must supply an admitted account/tenant/grant decision after authenticated
4//! OAuth has verified the source token and both possession signatures. This API
5//! is not a verifier: never pass a deserialized browser request directly to it.
6//! The caller supplies a dedicated, TLS-verified PostgreSQL connection under the
7//! narrow runtime role. No DSN or token bodies are accepted or logged here.
8
9use tokio_postgres::{error::SqlState, Client, IsolationLevel, Row};
10pub mod primary;
11
12pub const PROFILE: &str = "federate-session-v1";
13pub const SUITE: &str = "hs-cose-sign-ed25519-mldsa65-wns-v1";
14pub const MIGRATION: &str = include_str!("../sql/001_admission.sql");
15pub const ROLE_GRANTS: &str = include_str!("../sql/roles.sql");
16pub const MIGRATION_V2: &str = include_str!("../sql/002_epoch_inventory.sql");
17pub const ROLE_GRANTS_V2: &str = include_str!("../sql/002_roles.sql");
18pub const MIGRATION_V3: &str = include_str!("../sql/003_primary_lookup_index.sql");
19pub const MIGRATION_V4: &str = include_str!("../sql/004_atproto_source_did.sql");
20pub const MIGRATION_V5: &str = include_str!("../sql/005_identity_binding.sql");
21pub const ROLE_GRANTS_V5: &str = include_str!("../sql/005_roles.sql");
22
23/// Sanitized failures: PostgreSQL detail strings can include bound values.
24#[derive(Debug, thiserror::Error, PartialEq, Eq)]
25pub enum Error {
26    #[error("admission input invalid")]
27    Invalid,
28    #[error("profile disabled, missing or generation mismatch")]
29    Inactive,
30    #[error("source, challenge or grant expired")]
31    Expired,
32    #[error("source or session already consumed")]
33    Conflict,
34    #[error("session authority unavailable")]
35    Unavailable,
36}
37
38impl From<tokio_postgres::Error> for Error {
39    fn from(e: tokio_postgres::Error) -> Self {
40        if e.code() == Some(&SqlState::UNIQUE_VIOLATION) {
41            Self::Conflict
42        } else {
43            Self::Unavailable
44        }
45    }
46}
47
48/// Upstream-verified source metadata; never the raw ID token.
49#[derive(Clone, PartialEq, Eq)]
50pub struct Source {
51    pub issuer: String,
52    pub subject: String,
53    pub atproto_did: String,
54    pub jti: String,
55    pub nonce: String,
56    pub token_hash: [u8; 32],
57    pub issued_at: i64,
58    pub expires_at: i64,
59}
60
61/// Policy's authoritative pre-admission decision. No epoch can be supplied:
62/// PostgreSQL generates it only for a committed session.
63#[derive(Clone, PartialEq, Eq)]
64pub struct PendingSession {
65    pub host: String,
66    pub sid: String,
67    pub account_id: String,
68    pub subject: String,
69    pub tenant: String,
70    pub client_id: String,
71    pub resource: String,
72    pub scopes: Vec<String>,
73    pub grant_revision: String,
74    pub ed_public: [u8; 32],
75    pub pq_public: Vec<u8>,
76    pub generation: [u8; 32],
77    /// Server-owned ID of the complete, locally validated collision inventory.
78    pub collision_inventory_id: [u8; 32],
79    pub expires_at: i64,
80}
81
82/// An admitted, immutable record returned only after the transaction commits.
83#[derive(Clone, PartialEq, Eq)]
84pub struct Session {
85    pub host: String,
86    pub sid: String,
87    pub account_id: String,
88    pub subject: String,
89    pub tenant: String,
90    pub client_id: String,
91    pub resource: String,
92    pub scopes: Vec<String>,
93    pub grant_revision: String,
94    pub ed_public: [u8; 32],
95    pub pq_public: Vec<u8>,
96    pub generation: [u8; 32],
97    pub collision_inventory_id: [u8; 32],
98    pub proof_epoch: i64,
99    pub expires_at: i64,
100}
101
102/// A full active session together with the one durable source identity that
103/// admitted it. Fields stay private so consumers obtain this binding only
104/// through [`Store::lookup_primary`], never from a browser DTO.
105pub struct PrimaryRecord {
106    session: Session,
107    source: Source,
108    created_at: i64,
109}
110
111impl PrimaryRecord {
112    pub fn session(&self) -> &Session {
113        &self.session
114    }
115
116    pub fn source_identity(&self) -> (&str, &str) {
117        (&self.source.issuer, &self.source.subject)
118    }
119
120    pub fn source_atproto_did(&self) -> &str {
121        &self.source.atproto_did
122    }
123
124    pub fn created_at(&self) -> i64 {
125        self.created_at
126    }
127}
128
129impl PendingSession {
130    fn admitted(&self, proof_epoch: i64) -> Result<Session, Error> {
131        if proof_epoch <= 0 {
132            return Err(Error::Unavailable);
133        }
134        Ok(Session {
135            host: self.host.clone(),
136            sid: self.sid.clone(),
137            account_id: self.account_id.clone(),
138            subject: self.subject.clone(),
139            tenant: self.tenant.clone(),
140            client_id: self.client_id.clone(),
141            resource: self.resource.clone(),
142            scopes: self.scopes.clone(),
143            grant_revision: self.grant_revision.clone(),
144            ed_public: self.ed_public,
145            pq_public: self.pq_public.clone(),
146            generation: self.generation,
147            collision_inventory_id: self.collision_inventory_id,
148            proof_epoch,
149            expires_at: self.expires_at,
150        })
151    }
152}
153
154pub struct Admission {
155    pub session: PendingSession,
156    pub source: Source,
157    /// Independently loaded, complete local inventory. Never browser input.
158    pub local_collision_inventory_id: [u8; 32],
159    /// Expiry of the server-owned pending challenge, not supplied by a browser.
160    pub challenge_created_at: i64,
161    pub challenge_expires_at: i64,
162    pub grant_expires_at: i64,
163}
164
165fn bounded(s: &str, max: usize) -> bool {
166    !s.is_empty() && s.len() <= max && !s.contains('\0')
167}
168
169impl Admission {
170    fn validate(&self, now: i64) -> Result<i64, Error> {
171        let s = &self.session;
172        let src = &self.source;
173        if !bounded(&s.host, 2048)
174            || !bounded(&s.resource, 2048)
175            || !bounded(&src.issuer, 2048)
176            || !bounded(&s.sid, 128)
177            || [
178                &s.account_id,
179                &s.subject,
180                &s.tenant,
181                &s.client_id,
182                &s.grant_revision,
183                &src.subject,
184                &src.atproto_did,
185                &src.jti,
186                &src.nonce,
187            ]
188            .iter()
189            .any(|v| !bounded(v, 256))
190            || s.pq_public.len() != 1952
191            || s.scopes.is_empty()
192            || s.scopes.len() > 64
193            || s.scopes
194                .iter()
195                .any(|v| !bounded(v, 256) || !v.bytes().all(|b| (0x21..=0x7e).contains(&b)))
196            || s.scopes.windows(2).any(|w| w[0] >= w[1])
197            || src.issued_at < 0
198            || src.expires_at <= src.issued_at
199            || s.subject != src.atproto_did
200            || src
201                .expires_at
202                .checked_sub(src.issued_at)
203                .ok_or(Error::Invalid)?
204                > 300
205        {
206            return Err(Error::Invalid);
207        }
208        let age = now.checked_sub(src.issued_at).ok_or(Error::Invalid)?;
209        if !(-30..=120).contains(&age)
210            || now >= src.expires_at
211            || self.challenge_created_at > now
212            || self.challenge_created_at < 0
213            || self
214                .challenge_expires_at
215                .checked_sub(self.challenge_created_at)
216                .ok_or(Error::Invalid)?
217                > 60
218            || now >= self.challenge_expires_at
219            || now >= s.expires_at
220            || s.expires_at > self.grant_expires_at
221            || s.expires_at > src.expires_at
222            || s.expires_at.checked_sub(now).ok_or(Error::Invalid)? > 300
223            || self.challenge_expires_at > src.expires_at
224            || self.challenge_expires_at > src.issued_at.checked_add(120).ok_or(Error::Invalid)?
225        {
226            return Err(Error::Expired);
227        }
228        Ok(src
229            .issued_at
230            .checked_add(330)
231            .ok_or(Error::Invalid)?
232            .max(src.expires_at.checked_add(30).ok_or(Error::Invalid)?)
233            .max(s.expires_at))
234    }
235}
236
237/// Owns no pool or fallback authority. A dedicated connection is borrowed per
238/// operation; caller cancellation drops/rolls back the transaction. Commit errors
239/// (including ambiguous commit outcome) never return a usable admission receipt.
240pub struct Store;
241
242impl Store {
243    pub async fn admit(client: &mut Client, admission: &Admission) -> Result<Session, Error> {
244        let tx = client
245            .build_transaction()
246            .isolation_level(IsolationLevel::ReadCommitted)
247            .start()
248            .await?;
249        // Bound lock/statement time. No parameter values are included in errors.
250        tx.batch_execute("SET LOCAL lock_timeout = '2s'; SET LOCAL statement_timeout = '2s'")
251            .await?;
252        let version: i32 = tx
253            .query_one("SELECT version FROM federate_session.schema_version", &[])
254            .await?
255            .try_get(0)?;
256        if version != 5 {
257            return Err(Error::Unavailable);
258        }
259        let s = &admission.session;
260        let row = tx.query_opt(
261            "SELECT enabled, authority_generation, collision_inventory_id FROM federate_session.profile_state WHERE host=$1 AND profile=$2 FOR UPDATE",
262            &[&s.host, &PROFILE],
263        ).await?.ok_or(Error::Inactive)?;
264        let enabled: bool = row.try_get(0)?;
265        let generation: Vec<u8> = row.try_get(1)?;
266        let inventory: Vec<u8> = row.try_get(2)?;
267        if !enabled
268            || generation != s.generation
269            || inventory != s.collision_inventory_id
270            || inventory != admission.local_collision_inventory_id
271        {
272            return Err(Error::Inactive);
273        }
274        // PostgreSQL transaction timestamps precede lock waits; use clock_timestamp.
275        let now: i64 = tx
276            .query_one(
277                "SELECT floor(extract(epoch FROM clock_timestamp()))::bigint",
278                &[],
279            )
280            .await?
281            .try_get(0)?;
282        let retain_until = admission.validate(now)?;
283        let src = &admission.source;
284        tx.execute(
285            "INSERT INTO federate_session.identity_bindings (host,profile,issuer,source_subject,atproto_did,account_id,first_seen_at) VALUES ($1,$2,$3,$4,$5,$6,$7) ON CONFLICT DO NOTHING",
286            &[&s.host,&PROFILE,&src.issuer,&src.subject,&src.atproto_did,&s.account_id,&now],
287        ).await?;
288        let binding_matches = tx.query_opt(
289            "SELECT 1 FROM federate_session.identity_bindings WHERE host=$1 AND profile=$2 AND issuer=$3 AND source_subject=$4 AND atproto_did=$5 AND account_id=$6",
290            &[&s.host,&PROFILE,&src.issuer,&src.subject,&src.atproto_did,&s.account_id],
291        ).await?.is_some();
292        if !binding_matches {
293            return Err(Error::Conflict);
294        }
295        let proof_epoch: i64 = tx.query_one(
296            "INSERT INTO federate_session.sessions (host,profile,sid,account_id,subject,tenant,client_id,resource,scopes,grant_revision,suite,ed_public,pq_public,generation,collision_inventory_id,created_at,expires_at) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17) RETURNING proof_epoch",
297            &[&s.host,&PROFILE,&s.sid,&s.account_id,&s.subject,&s.tenant,&s.client_id,&s.resource,&s.scopes,&s.grant_revision,&SUITE,&&s.ed_public[..],&s.pq_public,&generation,&inventory,&now,&s.expires_at],
298        ).await?.try_get(0)?;
299        let admitted = s.admitted(proof_epoch)?;
300        tx.execute(
301            "INSERT INTO federate_session.replay (issuer,client_id,jti,nonce,token_hash,source_iat,source_exp,retain_until,host,sid,source_subject,source_atproto_did) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12)",
302            &[&src.issuer,&s.client_id,&src.jti,&src.nonce,&&src.token_hash[..],&src.issued_at,&src.expires_at,&retain_until,&s.host,&s.sid,&src.subject,&src.atproto_did],
303        ).await?;
304        tx.commit().await?;
305        Ok(admitted)
306    }
307
308    /// Resolve by issuer/sid and compare the complete expected credential binding.
309    /// No positive cache and no static-primary fallback. SQL/schema errors deny.
310    pub async fn active(client: &Client, expected: &Session) -> Result<bool, Error> {
311        Ok(Self::lookup(
312            client,
313            &expected.host,
314            &expected.sid,
315            &expected.generation,
316            &expected.collision_inventory_id,
317        )
318        .await?
319        .as_ref()
320            == Some(expected))
321    }
322
323    /// Authoritative full-record lookup for the future request-local proof resolver.
324    /// The session must have its own matching, verified source-DID replay record
325    /// and immutable identity binding. Caller must still compare all credential
326    /// fields and verify the RPC proof.
327    pub async fn lookup(
328        client: &(impl tokio_postgres::GenericClient + Sync),
329        host: &str,
330        sid: &str,
331        generation: &[u8; 32],
332        local_collision_inventory_id: &[u8; 32],
333    ) -> Result<Option<Session>, Error> {
334        let row = client.query_opt(
335            "SELECT s.* FROM federate_session.sessions s JOIN federate_session.profile_state p ON (s.host=p.host AND s.profile=p.profile) JOIN federate_session.replay r ON (r.host=s.host AND r.sid=s.sid AND r.client_id=s.client_id) JOIN federate_session.identity_bindings b ON (b.host=s.host AND b.profile=s.profile AND b.issuer=r.issuer AND b.source_subject=r.source_subject AND b.atproto_did=r.source_atproto_did AND b.account_id=s.account_id) WHERE s.host=$1 AND s.sid=$2 AND s.profile=$3 AND s.suite=$4 AND s.status='active' AND p.enabled AND s.generation=p.authority_generation AND s.generation=$5 AND s.collision_inventory_id=p.collision_inventory_id AND s.collision_inventory_id=$6 AND s.proof_epoch>0 AND s.expires_at>floor(extract(epoch FROM clock_timestamp()))::bigint AND r.source_atproto_did IS NOT NULL AND s.subject=r.source_atproto_did",
336            &[&host,&sid,&PROFILE,&SUITE,&&generation[..],&&local_collision_inventory_id[..]],
337        ).await?;
338        row.as_ref().map(read_session).transpose()
339    }
340
341    /// Resolve the exact active session and its unique, committed source
342    /// identity in one query. A session without exactly one matching replay
343    /// row fails closed; callers still bind the full record to verified host
344    /// JWT claims and holder proof before dispatch.
345    pub async fn lookup_primary(
346        client: &mut Client,
347        host: &str,
348        sid: &str,
349        generation: &[u8; 32],
350        local_collision_inventory_id: &[u8; 32],
351    ) -> Result<Option<PrimaryRecord>, Error> {
352        let tx = client
353            .build_transaction()
354            .isolation_level(IsolationLevel::ReadCommitted)
355            .start()
356            .await?;
357        // Bound backend work even if the caller cancels its future. The index
358        // migration below supports the replay-side equality join.
359        tx.batch_execute("SET LOCAL statement_timeout = '2s'")
360            .await?;
361        let version: i32 = tx
362            .query_one("SELECT version FROM federate_session.schema_version", &[])
363            .await?
364            .try_get(0)?;
365        if version != 5 {
366            return Err(Error::Unavailable);
367        }
368        let rows = tx.query(
369            "SELECT s.*, r.issuer AS source_issuer, r.source_subject, r.source_atproto_did, r.jti AS source_jti, r.nonce AS source_nonce, r.token_hash AS source_token_hash, r.source_iat, r.source_exp FROM federate_session.sessions s JOIN federate_session.profile_state p ON (s.host=p.host AND s.profile=p.profile) JOIN federate_session.replay r ON (r.host=s.host AND r.sid=s.sid AND r.client_id=s.client_id) JOIN federate_session.identity_bindings b ON (b.host=s.host AND b.profile=s.profile AND b.issuer=r.issuer AND b.source_subject=r.source_subject AND b.atproto_did=r.source_atproto_did AND b.account_id=s.account_id) WHERE s.host=$1 AND s.sid=$2 AND s.profile=$3 AND s.suite=$4 AND s.status='active' AND p.enabled AND s.generation=p.authority_generation AND s.generation=$5 AND s.collision_inventory_id=p.collision_inventory_id AND s.collision_inventory_id=$6 AND s.proof_epoch>0 AND s.expires_at>floor(extract(epoch FROM clock_timestamp()))::bigint AND r.source_atproto_did IS NOT NULL AND s.subject=r.source_atproto_did LIMIT 2",
370            &[&host, &sid, &PROFILE, &SUITE, &&generation[..], &&local_collision_inventory_id[..]],
371        ).await?;
372        let result = match rows.len() {
373            0 => Ok(None),
374            1 => {
375                let row = &rows[0];
376                let session = read_session(row)?;
377                let source = Source {
378                    issuer: row.try_get("source_issuer")?,
379                    subject: row.try_get("source_subject")?,
380                    atproto_did: row.try_get("source_atproto_did")?,
381                    jti: row.try_get("source_jti")?,
382                    nonce: row.try_get("source_nonce")?,
383                    token_hash: row
384                        .try_get::<_, Vec<u8>>("source_token_hash")?
385                        .try_into()
386                        .map_err(|_| Error::Unavailable)?,
387                    issued_at: row.try_get("source_iat")?,
388                    expires_at: row.try_get("source_exp")?,
389                };
390                Ok(Some(PrimaryRecord {
391                    session,
392                    source,
393                    created_at: row.try_get("created_at")?,
394                }))
395            }
396            _ => Err(Error::Unavailable),
397        };
398        tx.commit().await?;
399        result
400    }
401
402    /// Atomically consumes an already-verified v16 `(namespace, request_id)`
403    /// against the current exact session. The caller must derive `namespace`
404    /// from the verified suite, ordered public components and stored epoch;
405    /// this store neither parses proofs nor offers a runtime verifier factory.
406    /// Unknown commit outcomes deny; no local-cache fallback is possible.
407    pub async fn consume_request_replay(
408        client: &mut Client,
409        expected: &Session,
410        verified_namespace: &[u8; 32],
411        request_id: &[u8; 16],
412        configured_clock_skew_secs: i64,
413    ) -> Result<(), Error> {
414        if expected.proof_epoch <= 0 || configured_clock_skew_secs < 0 {
415            return Err(Error::Invalid);
416        }
417        let retain_until = expected
418            .expires_at
419            .checked_add(configured_clock_skew_secs)
420            .ok_or(Error::Invalid)?;
421        let tx = client
422            .build_transaction()
423            .isolation_level(IsolationLevel::ReadCommitted)
424            .start()
425            .await?;
426        tx.batch_execute("SET LOCAL lock_timeout = '2s'; SET LOCAL statement_timeout = '2s'")
427            .await?;
428        let version: i32 = tx
429            .query_one("SELECT version FROM federate_session.schema_version", &[])
430            .await?
431            .try_get(0)?;
432        if version != 5 {
433            return Err(Error::Unavailable);
434        }
435        let profile = tx.query_opt(
436            "SELECT enabled, authority_generation, collision_inventory_id FROM federate_session.profile_state WHERE host=$1 AND profile=$2 FOR UPDATE",
437            &[&expected.host, &PROFILE],
438        ).await?.ok_or(Error::Inactive)?;
439        let enabled: bool = profile.try_get(0)?;
440        let generation: Vec<u8> = profile.try_get(1)?;
441        let inventory: Vec<u8> = profile.try_get(2)?;
442        if !enabled
443            || generation != expected.generation
444            || inventory != expected.collision_inventory_id
445        {
446            return Err(Error::Inactive);
447        }
448        let row = tx.query_opt(
449            "SELECT * FROM federate_session.sessions WHERE host=$1 AND sid=$2 AND profile=$3 AND suite=$4 AND status='active' FOR SHARE",
450            &[&expected.host, &expected.sid, &PROFILE, &SUITE],
451        ).await?.ok_or(Error::Inactive)?;
452        if &read_session(&row)? != expected {
453            return Err(Error::Inactive);
454        }
455        let now: i64 = tx
456            .query_one(
457                "SELECT floor(extract(epoch FROM clock_timestamp()))::bigint",
458                &[],
459            )
460            .await?
461            .try_get(0)?;
462        if now >= expected.expires_at {
463            return Err(Error::Expired);
464        }
465        tx.execute(
466            "INSERT INTO federate_session.request_replay (verified_namespace,request_id,retain_until) VALUES ($1,$2,$3)",
467            &[&&verified_namespace[..], &&request_id[..], &retain_until],
468        ).await?;
469        tx.commit().await?;
470        Ok(())
471    }
472
473    pub async fn revoke(
474        client: &Client,
475        host: &str,
476        sid: &str,
477        generation: &[u8; 32],
478    ) -> Result<bool, Error> {
479        Ok(client.execute(
480            "UPDATE federate_session.sessions SET status='revoked' WHERE host=$1 AND sid=$2 AND generation=$3 AND profile=$4",
481            &[&host,&sid,&&generation[..],&PROFILE],
482        ).await? == 1)
483    }
484
485    /// Maintenance-role only; one transaction, expired replay first. Runtime
486    /// has no DELETE privilege. No active or replay-protected session is removed.
487    pub async fn cleanup(client: &mut Client) -> Result<(), Error> {
488        let tx = client.transaction().await?;
489        tx.execute("DELETE FROM federate_session.request_replay WHERE retain_until<floor(extract(epoch FROM clock_timestamp()))::bigint", &[]).await?;
490        tx.execute("DELETE FROM federate_session.replay WHERE retain_until<floor(extract(epoch FROM clock_timestamp()))::bigint", &[]).await?;
491        tx.execute("DELETE FROM federate_session.sessions s WHERE expires_at<floor(extract(epoch FROM clock_timestamp()))::bigint AND NOT EXISTS (SELECT 1 FROM federate_session.replay r WHERE r.host=s.host AND r.sid=s.sid)", &[]).await?;
492        tx.commit().await?;
493        Ok(())
494    }
495}
496
497fn read_session(row: &Row) -> Result<Session, Error> {
498    Ok(Session {
499        host: row.try_get("host")?,
500        sid: row.try_get("sid")?,
501        account_id: row.try_get("account_id")?,
502        subject: row.try_get("subject")?,
503        tenant: row.try_get("tenant")?,
504        client_id: row.try_get("client_id")?,
505        resource: row.try_get("resource")?,
506        scopes: row.try_get("scopes")?,
507        grant_revision: row.try_get("grant_revision")?,
508        ed_public: row
509            .try_get::<_, Vec<u8>>("ed_public")?
510            .try_into()
511            .map_err(|_| Error::Unavailable)?,
512        pq_public: row.try_get("pq_public")?,
513        generation: row
514            .try_get::<_, Vec<u8>>("generation")?
515            .try_into()
516            .map_err(|_| Error::Unavailable)?,
517        collision_inventory_id: row
518            .try_get::<_, Vec<u8>>("collision_inventory_id")?
519            .try_into()
520            .map_err(|_| Error::Unavailable)?,
521        proof_epoch: {
522            let epoch: i64 = row.try_get("proof_epoch")?;
523            if epoch <= 0 {
524                return Err(Error::Unavailable);
525            }
526            epoch
527        },
528        expires_at: row.try_get("expires_at")?,
529    })
530}