oxedyne/fe2o3/fe2o3_steel/src/srv/member/session.rs
24.9 KiB, 24 runs
created by r1870400018:72144, which is this file's identity for as long as the history lasts, whatever it is later renamed to
download · who wrote it · its history
| 1 | //! Server-side sessions for a site's signed-in members, kept in the vhost's Ozone store. |
| 2 | //! |
| 3 | //! A session survives a restart, is ended at once by a sign-out or a revocation, and cannot be |
| 4 | //! recovered from a read of the store: the browser holds a 32-byte random token, and the store holds |
| 5 | //! only its SHA3-256 hash, as the key `<prefix>s/<hex hash>` -> `{ principal, data, created, |
| 6 | //! last_seen }`. One process owns the store, so the RAM map in front of it is the authority while |
| 7 | //! the process runs, and `Sessions::load` rebuilds it from one prefix scan at startup. |
| 8 | //! |
| 9 | //! # Audit against the Daimond gateway's sessions (2026-10-11) |
| 10 | //! |
| 11 | //! The gateway (`daimond/gateway/src/schema.rs` `sess:` keys, `handlers/{auth_verify,common}.rs`) |
| 12 | //! and Steel's admin cookie (`srv/admin/session.rs`) were read first. Each behaviour, kept or |
| 13 | //! changed: |
| 14 | //! |
| 15 | //! - **Token form: changed.** The gateway mints a 32-character random string and stores it raw |
| 16 | //! as the key `sess:<token>`, so anyone who reads the store or a dump of it holds every live |
| 17 | //! session. Here the token is 32 random bytes and only its hash is stored. |
| 18 | //! - **What is stored: changed.** The gateway keeps `{ account_id, issued_ts, exp }`. Here the |
| 19 | //! record holds the principal as bytes, an app's own `data`, `created` and `last_seen`; expiry |
| 20 | //! is computed from the config rather than frozen into the record, so a changed window applies |
| 21 | //! to every session at once. |
| 22 | //! - **Expiry: kept.** An idle window plus an absolute ceiling, the ceiling enforced on read, not |
| 23 | //! only by the writer, is the gateway's design and is right. |
| 24 | //! - **Slide throttle: kept.** The gateway writes a slide only when it moves `exp` by more than |
| 25 | //! `SESSION_SLIDE_MIN_SECS`; here `last_seen` is written at most once per `touch_secs`. The RAM |
| 26 | //! copy is exact, so a restart costs a session at most `touch_secs` of idle time. |
| 27 | //! - **No resurrection: kept.** The gateway's slide re-reads under a lock so that a sign-out |
| 28 | //! between read and write stays a sign-out. Here every write happens under the state lock and |
| 29 | //! only for a session the RAM map still holds, so a touch cannot write back an ended session. |
| 30 | //! - **Per-principal cap: added.** The gateway has none, so a principal's sessions grow without |
| 31 | //! bound until each one expires. Here the oldest is dropped past `per_principal`. |
| 32 | //! - **Revocation: added.** The gateway ends one session by its token; it cannot end every |
| 33 | //! session of one account. `end_all` and `end_id` do. |
| 34 | //! - **Sweep: added.** The gateway deletes an expired record only when its own token is next |
| 35 | //! presented, so an abandoned session's record stays forever. `sweep` removes every expired one, |
| 36 | //! and `load` drops those it finds. |
| 37 | //! - **Logging: kept.** The gateway logs the account on sign-in and never the token; here the log |
| 38 | //! names a session by the first eight hex characters of its hash and never the token. |
| 39 | //! - **The admin cookie: not reused.** Stateless and encrypted under a key that rotates on restart, |
| 40 | //! it cannot survive a restart or be revoked singly, which members need. |
| 41 | //! |
| 42 | //! The gateway's store is `O3db` with the same type parameters as `VhostDb`, so a migration needs |
| 43 | //! only its `Store` to hand over its `Arc<RwLock<GwDb>>` and a `Uid`. Its live `sess:` records |
| 44 | //! move without a sign-in: the migration holds each raw token, so `Token::from_secret` of those |
| 45 | //! 32 bytes and `Sessions::adopt` write the hashed record with the old creation and last-use |
| 46 | //! times, each expiry carried exactly, and the raw record is then deleted. The browser keeps the |
| 47 | //! cookie it has. Steel's own WebSocket member login (`sess_meta:<sid>`) also stores its id raw |
| 48 | //! and is a candidate for the same move. |
| 49 | //! |
| 50 | //! A request that must not count as use (a background wake, a socket's re-check) authenticates |
| 51 | //! with `peek`, which ends an expired session as `check` does but never moves `last_seen`. |
| 52 | |
| 53 | pub use super::{ |
| 54 | Clock, |
| 55 | Token, |
| 56 | TOKEN_LEN, |
| 57 | }; |
| 58 | |
| 59 | use super::{ |
| 60 | Hash32, |
| 61 | hash_of_key, |
| 62 | hex, |
| 63 | short, |
| 64 | }; |
| 65 | use crate::{ |
| 66 | app::server::VhostDb, |
| 67 | srv::id::Uid, |
| 68 | }; |
| 69 | |
| 70 | use oxedyne_fe2o3_core::prelude::*; |
| 71 | use oxedyne_fe2o3_iop_db::api::{ |
| 72 | Database, |
| 73 | ScanOpts, |
| 74 | }; |
| 75 | use oxedyne_fe2o3_jdat::prelude::*; |
| 76 | |
| 77 | use std::{ |
| 78 | collections::{ |
| 79 | BTreeSet, |
| 80 | HashMap, |
| 81 | }, |
| 82 | sync::{ |
| 83 | Arc, |
| 84 | Mutex, |
| 85 | RwLock, |
| 86 | }, |
| 87 | }; |
| 88 | |
| 89 | #[derive(Clone, Debug)] |
| 90 | pub struct SessionCfg { |
| 91 | pub prefix: String, // keys are `<prefix>s/<hex hash>` |
| 92 | pub idle_secs: u64, |
| 93 | pub absolute_secs: u64, |
| 94 | pub per_principal: usize, // at least 1 |
| 95 | pub touch_secs: u64, // least gap between two `last_seen` writes |
| 96 | } |
| 97 | |
| 98 | impl Default for SessionCfg { |
| 99 | fn default() -> Self { |
| 100 | Self { |
| 101 | prefix: fmt!("member/"), |
| 102 | idle_secs: 14 * 86_400, |
| 103 | absolute_secs: 90 * 86_400, |
| 104 | per_principal: 10, |
| 105 | touch_secs: 600, |
| 106 | } |
| 107 | } |
| 108 | } |
| 109 | |
| 110 | impl SessionCfg { |
| 111 | pub fn check(&self) -> Outcome<()> { |
| 112 | if self.idle_secs == 0 || self.absolute_secs == 0 { |
| 113 | return Err(err!( |
| 114 | "SessionCfg: idle_secs ({}) and absolute_secs ({}) must both be above zero.", |
| 115 | self.idle_secs, self.absolute_secs; |
| 116 | Invalid, Input)); |
| 117 | } |
| 118 | if self.per_principal == 0 { |
| 119 | return Err(err!("SessionCfg: per_principal must be at least 1."; Invalid, Input)); |
| 120 | } |
| 121 | Ok(()) |
| 122 | } |
| 123 | |
| 124 | fn key_prefix(&self) -> String { |
| 125 | fmt!("{}s/", self.prefix) |
| 126 | } |
| 127 | |
| 128 | fn key(&self, hash: &Hash32) -> Dat { |
| 129 | Dat::Str(fmt!("{}{}", self.key_prefix(), hex(hash))) |
| 130 | } |
| 131 | } |
| 132 | |
| 133 | /// A live session as a caller sees it. `id` is the hex hash of the token: it names the session, |
| 134 | /// for a list of a member's devices say, and cannot be used to present it. |
| 135 | #[derive(Clone, Debug, PartialEq)] |
| 136 | pub struct Session { |
| 137 | pub id: String, |
| 138 | pub principal: Vec<u8>, |
| 139 | pub data: Dat, |
| 140 | pub created: u64, // Unix seconds |
| 141 | pub last_seen: u64, // Unix seconds |
| 142 | } |
| 143 | |
| 144 | #[derive(Clone)] |
| 145 | struct Entry { |
| 146 | principal: Vec<u8>, |
| 147 | data: Dat, |
| 148 | created: u64, |
| 149 | last_seen: u64, |
| 150 | stored_seen: u64, // `last_seen` as the store holds it |
| 151 | } |
| 152 | |
| 153 | impl Entry { |
| 154 | fn to_dat(&self, last_seen: u64) -> Dat { |
| 155 | let mut m = DaticleMap::new(); |
| 156 | m.insert(dat!("principal"), Dat::BU64(self.principal.clone())); |
| 157 | m.insert(dat!("data"), self.data.clone()); |
| 158 | m.insert(dat!("created"), Dat::U64(self.created)); |
| 159 | m.insert(dat!("last_seen"), Dat::U64(last_seen)); |
| 160 | Dat::Map(m) |
| 161 | } |
| 162 | |
| 163 | fn from_dat(d: &Dat) -> Outcome<Self> { |
| 164 | let m = match d { |
| 165 | Dat::Map(m) => m, |
| 166 | _ => return Err(err!( |
| 167 | "A member session record is not a map: {:?}.", d.kind(); |
| 168 | Invalid, Input, Decode)), |
| 169 | }; |
| 170 | let principal = match m.get(&dat!("principal")).and_then(|p| p.bytes_ref()) { |
| 171 | Some(b) => b.clone(), |
| 172 | None => return Err(err!( |
| 173 | "A member session record has no principal bytes."; Missing, Input, Decode)), |
| 174 | }; |
| 175 | let num = |name: &str| -> Outcome<u64> { |
| 176 | match m.get(&dat!(name)) { |
| 177 | Some(Dat::U64(n)) => Ok(*n), |
| 178 | other => Err(err!( |
| 179 | "A member session record's '{}' is not a u64: {:?}.", name, other; |
| 180 | Invalid, Input, Decode)), |
| 181 | } |
| 182 | }; |
| 183 | let created = res!(num("created")); |
| 184 | let last_seen = res!(num("last_seen")); |
| 185 | Ok(Self { |
| 186 | principal, |
| 187 | data: m.get(&dat!("data")).cloned().unwrap_or(Dat::Empty), |
| 188 | created, |
| 189 | last_seen, |
| 190 | stored_seen: last_seen, |
| 191 | }) |
| 192 | } |
| 193 | |
| 194 | fn session(&self, hash: &Hash32) -> Session { |
| 195 | Session { |
| 196 | id: hex(hash), |
| 197 | principal: self.principal.clone(), |
| 198 | data: self.data.clone(), |
| 199 | created: self.created, |
| 200 | last_seen: self.last_seen, |
| 201 | } |
| 202 | } |
| 203 | } |
| 204 | |
| 205 | #[derive(Default)] |
| 206 | struct State { |
| 207 | by_hash: HashMap<Hash32, Entry>, |
| 208 | by_principal: HashMap<Vec<u8>, BTreeSet<(u64, Hash32)>>, // oldest first |
| 209 | } |
| 210 | |
| 211 | impl State { |
| 212 | fn add(&mut self, hash: Hash32, e: Entry) { |
| 213 | self.by_principal.entry(e.principal.clone()).or_default().insert((e.created, hash)); |
| 214 | self.by_hash.insert(hash, e); |
| 215 | } |
| 216 | |
| 217 | fn remove(&mut self, hash: &Hash32) -> Option<Entry> { |
| 218 | let e = match self.by_hash.remove(hash) { |
| 219 | Some(e) => e, |
| 220 | None => return None, |
| 221 | }; |
| 222 | let empty = match self.by_principal.get_mut(&e.principal) { |
| 223 | Some(set) => { |
| 224 | set.remove(&(e.created, *hash)); |
| 225 | set.is_empty() |
| 226 | } |
| 227 | None => false, |
| 228 | }; |
| 229 | if empty { |
| 230 | self.by_principal.remove(&e.principal); |
| 231 | } |
| 232 | Some(e) |
| 233 | } |
| 234 | } |
| 235 | |
| 236 | /// The sessions of one vhost's members: an in-RAM map in front of the store. |
| 237 | /// |
| 238 | /// Every write is awaited until the store confirms it durable (`Database::insert` and `delete` |
| 239 | /// wait on `Responder::recv_store_ack` and `recv_delete_ack`), and is made under the state lock, |
| 240 | /// so the store and the map change together and two requests cannot interleave a change. |
| 241 | pub struct Sessions { |
| 242 | cfg: SessionCfg, |
| 243 | clock: Clock, |
| 244 | state: Mutex<State>, |
| 245 | } |
| 246 | |
| 247 | impl Sessions { |
| 248 | /// Rebuilds the sessions from one scan of `cfg.prefix`, dropping any that have expired. For |
| 249 | /// startup only: the scan walks the whole store. |
| 250 | pub fn load(db: &(Arc<RwLock<VhostDb>>, Uid), cfg: SessionCfg) -> Outcome<Self> { |
| 251 | Self::load_with_clock(db, cfg, Clock::System) |
| 252 | } |
| 253 | |
| 254 | pub fn load_with_clock( |
| 255 | db: &(Arc<RwLock<VhostDb>>, Uid), |
| 256 | cfg: SessionCfg, |
| 257 | clock: Clock, |
| 258 | ) |
| 259 | -> Outcome<Self> |
| 260 | { |
| 261 | res!(cfg.check()); |
| 262 | let now = res!(clock.now()); |
| 263 | let (db_arc, uid) = db; |
| 264 | let mut state = State::default(); |
| 265 | let mut dropped = 0usize; |
| 266 | { |
| 267 | let dbr = lock_read!(db_arc); |
| 268 | let keys = res!(dbr.scan(&ScanOpts::with_str_prefix(cfg.key_prefix()), None)); |
| 269 | for (key, _, _) in keys { |
| 270 | let name = match &key { |
| 271 | Dat::Str(s) => s.clone(), |
| 272 | _ => continue, |
| 273 | }; |
| 274 | let hash = match hash_of_key(&name[cfg.key_prefix().len()..]) { |
| 275 | Some(h) => h, |
| 276 | None => { |
| 277 | warn!("member session: load: '{}' is not a session key; left alone.", name); |
| 278 | continue; |
| 279 | } |
| 280 | }; |
| 281 | // A key the scan listed that reads as absent is a deleted record. |
| 282 | let val = match res!(dbr.get(&key, None)) { |
| 283 | Some((v, _)) => v, |
| 284 | None => continue, |
| 285 | }; |
| 286 | let e = match Entry::from_dat(&val) { |
| 287 | Ok(e) => e, |
| 288 | Err(e) => { |
| 289 | warn!("member session: load: {} is unreadable and is dropped: {}", |
| 290 | short(&hash), e); |
| 291 | res!(dbr.delete(&key, uid.clone(), None)); |
| 292 | dropped += 1; |
| 293 | continue; |
| 294 | } |
| 295 | }; |
| 296 | if expired(&cfg, &e, now) { |
| 297 | res!(dbr.delete(&key, uid.clone(), None)); |
| 298 | dropped += 1; |
| 299 | continue; |
| 300 | } |
| 301 | state.add(hash, e); |
| 302 | } |
| 303 | } |
| 304 | info!("member session: loaded {} live under '{}', dropped {} expired or unreadable.", |
| 305 | state.by_hash.len(), cfg.prefix, dropped); |
| 306 | Ok(Self { |
| 307 | cfg, |
| 308 | clock, |
| 309 | state: Mutex::new(state), |
| 310 | }) |
| 311 | } |
| 312 | |
| 313 | pub fn cfg(&self) -> &SessionCfg { &self.cfg } |
| 314 | |
| 315 | /// Opens a session for `principal`, first ending its oldest where it already holds |
| 316 | /// `per_principal`. |
| 317 | pub fn start( |
| 318 | &self, |
| 319 | db: &(Arc<RwLock<VhostDb>>, Uid), |
| 320 | principal: &[u8], |
| 321 | data: Dat, |
| 322 | ) |
| 323 | -> Outcome<Token> |
| 324 | { |
| 325 | let now = res!(self.clock.now()); |
| 326 | let token = Token::generate(); |
| 327 | let hash = res!(token.hash()); |
| 328 | let e = Entry { |
| 329 | principal: principal.to_vec(), |
| 330 | data, |
| 331 | created: now, |
| 332 | last_seen: now, |
| 333 | stored_seen: now, |
| 334 | }; |
| 335 | let (db_arc, uid) = db; |
| 336 | let mut state = lock_mutex!(self.state); |
| 337 | let dbr = lock_read!(db_arc); |
| 338 | // The cap is made room for before the write, so a failed delete leaves no new session. |
| 339 | loop { |
| 340 | let oldest = match state.by_principal.get(principal) { |
| 341 | Some(set) if set.len() >= self.cfg.per_principal => match set.iter().next() { |
| 342 | Some((_, h)) => *h, |
| 343 | None => break, |
| 344 | }, |
| 345 | _ => break, |
| 346 | }; |
| 347 | res!(dbr.delete(&self.cfg.key(&oldest), uid.clone(), None)); |
| 348 | state.remove(&oldest); |
| 349 | debug!("member session: {} ended, its principal's oldest past the cap of {}.", |
| 350 | short(&oldest), self.cfg.per_principal); |
| 351 | } |
| 352 | res!(dbr.insert(self.cfg.key(&hash), e.to_dat(now), uid.clone(), None)); |
| 353 | state.add(hash, e); |
| 354 | debug!("member session: {} started.", short(&hash)); |
| 355 | Ok(token) |
| 356 | } |
| 357 | |
| 358 | /// Takes over a session issued elsewhere under a secret the caller holds, keeping its |
| 359 | /// `created` and `last_seen` (Unix seconds), so that both expiries fall exactly where they |
| 360 | /// would have. Whether it was written: an adoptee already expired under this config, or one |
| 361 | /// the per-principal cap would end first (it is older than every session the principal holds |
| 362 | /// at the cap), is not. |
| 363 | /// |
| 364 | /// Adopting a hash already held is a re-run: the record is rewritten with the earlier |
| 365 | /// `created` and the later `last_seen`, so an older copy cannot wind a session's use back. A |
| 366 | /// hash held for another principal is refused. Adoption cannot revive a revoked session for |
| 367 | /// anyone but a holder of its secret; a migration should therefore delete each raw record |
| 368 | /// once it is adopted, and never adopt from a copy older than its last revocation. |
| 369 | pub fn adopt( |
| 370 | &self, |
| 371 | db: &(Arc<RwLock<VhostDb>>, Uid), |
| 372 | token: &Token, |
| 373 | principal: &[u8], |
| 374 | data: Dat, |
| 375 | created: u64, |
| 376 | last_seen: u64, |
| 377 | ) |
| 378 | -> Outcome<bool> |
| 379 | { |
| 380 | let now = res!(self.clock.now()); |
| 381 | if last_seen < created || last_seen > now { |
| 382 | return Err(err!( |
| 383 | "Adopting a member session: last_seen {} must lie between created {} and now {}.", |
| 384 | last_seen, created, now; |
| 385 | Invalid, Input)); |
| 386 | } |
| 387 | let hash = res!(token.hash()); |
| 388 | let (db_arc, uid) = db; |
| 389 | let mut state = lock_mutex!(self.state); |
| 390 | let mut e = Entry { |
| 391 | principal: principal.to_vec(), |
| 392 | data, |
| 393 | created, |
| 394 | last_seen, |
| 395 | stored_seen: last_seen, |
| 396 | }; |
| 397 | if let Some(held) = state.by_hash.get(&hash) { |
| 398 | if held.principal != e.principal { |
| 399 | return Err(err!( |
| 400 | "Adopting member session {}: it is already held for another principal.", |
| 401 | short(&hash); |
| 402 | Invalid, Input, Exists)); |
| 403 | } |
| 404 | e.created = held.created.min(e.created); |
| 405 | e.last_seen = held.last_seen.max(e.last_seen); |
| 406 | e.stored_seen = e.last_seen; |
| 407 | } |
| 408 | if expired(&self.cfg, &e, now) { |
| 409 | debug!("member session: {} not adopted, already expired.", short(&hash)); |
| 410 | return Ok(false); |
| 411 | } |
| 412 | let dbr = lock_read!(db_arc); |
| 413 | // The cap as `start` applies it, oldest first, counting the adoptee in its place. |
| 414 | loop { |
| 415 | let oldest = match state.by_principal.get(principal) { |
| 416 | Some(set) => { |
| 417 | let others = set.iter().filter(|(_, h)| *h != hash).count(); |
| 418 | if others < self.cfg.per_principal { |
| 419 | break; |
| 420 | } |
| 421 | match set.iter().find(|(_, h)| *h != hash) { |
| 422 | Some(first) => *first, |
| 423 | None => break, |
| 424 | } |
| 425 | } |
| 426 | None => break, |
| 427 | }; |
| 428 | if (e.created, hash) < oldest { |
| 429 | debug!("member session: {} not adopted, older than its principal's {} held.", |
| 430 | short(&hash), self.cfg.per_principal); |
| 431 | return Ok(false); |
| 432 | } |
| 433 | res!(dbr.delete(&self.cfg.key(&oldest.1), uid.clone(), None)); |
| 434 | state.remove(&oldest.1); |
| 435 | debug!("member session: {} ended, its principal's oldest past the cap of {}.", |
| 436 | short(&oldest.1), self.cfg.per_principal); |
| 437 | } |
| 438 | res!(dbr.insert(self.cfg.key(&hash), e.to_dat(e.last_seen), uid.clone(), None)); |
| 439 | state.remove(&hash); // its index entry may carry the old `created` |
| 440 | state.add(hash, e); |
| 441 | debug!("member session: {} adopted.", short(&hash)); |
| 442 | Ok(true) |
| 443 | } |
| 444 | |
| 445 | /// The live session the token names, if any. An expired one is ended here; a live one has |
| 446 | /// `last_seen` moved to now, written through at most once per `touch_secs`. |
| 447 | pub fn check( |
| 448 | &self, |
| 449 | db: &(Arc<RwLock<VhostDb>>, Uid), |
| 450 | token: &Token, |
| 451 | ) |
| 452 | -> Outcome<Option<Session>> |
| 453 | { |
| 454 | self.find(db, token, true) |
| 455 | } |
| 456 | |
| 457 | /// As `check`, ending an expired session, but a live one is left exactly as it was: nothing |
| 458 | /// is written and `last_seen` does not move. For a request that must not count as use. |
| 459 | pub fn peek( |
| 460 | &self, |
| 461 | db: &(Arc<RwLock<VhostDb>>, Uid), |
| 462 | token: &Token, |
| 463 | ) |
| 464 | -> Outcome<Option<Session>> |
| 465 | { |
| 466 | self.find(db, token, false) |
| 467 | } |
| 468 | |
| 469 | fn find( |
| 470 | &self, |
| 471 | db: &(Arc<RwLock<VhostDb>>, Uid), |
| 472 | token: &Token, |
| 473 | touch: bool, |
| 474 | ) |
| 475 | -> Outcome<Option<Session>> |
| 476 | { |
| 477 | let now = res!(self.clock.now()); |
| 478 | let hash = res!(token.hash()); |
| 479 | let (db_arc, uid) = db; |
| 480 | let mut state = lock_mutex!(self.state); |
| 481 | let e = match state.by_hash.get(&hash) { |
| 482 | Some(e) => e.clone(), |
| 483 | None => return Ok(None), |
| 484 | }; |
| 485 | if expired(&self.cfg, &e, now) { |
| 486 | state.remove(&hash); |
| 487 | // Best effort: the map no longer holds it, so it is ended for this process, and a |
| 488 | // record left behind is dropped by the next sweep or load. |
| 489 | let dbr = lock_read!(db_arc); |
| 490 | if let Err(err) = dbr.delete(&self.cfg.key(&hash), uid.clone(), None) { |
| 491 | warn!("member session: {} expired but its record could not be deleted: {}", |
| 492 | short(&hash), err); |
| 493 | } |
| 494 | return Ok(None); |
| 495 | } |
| 496 | if !touch { |
| 497 | return Ok(Some(e.session(&hash))); |
| 498 | } |
| 499 | let mut stored_seen = e.stored_seen; |
| 500 | if now >= e.stored_seen.saturating_add(self.cfg.touch_secs) { |
| 501 | // Best effort too: a touch that could not be written costs this session up to |
| 502 | // `touch_secs` of idle time after a restart, not the request in hand. |
| 503 | let dbr = lock_read!(db_arc); |
| 504 | match dbr.insert(self.cfg.key(&hash), e.to_dat(now), uid.clone(), None) { |
| 505 | Ok(_) => stored_seen = now, |
| 506 | Err(err) => warn!("member session: {} could not record its use: {}", |
| 507 | short(&hash), err), |
| 508 | } |
| 509 | } |
| 510 | let live = match state.by_hash.get_mut(&hash) { |
| 511 | Some(live) => { |
| 512 | live.last_seen = now; |
| 513 | live.stored_seen = stored_seen; |
| 514 | live.clone() |
| 515 | } |
| 516 | None => return Ok(None), |
| 517 | }; |
| 518 | Ok(Some(live.session(&hash))) |
| 519 | } |
| 520 | |
| 521 | /// Replaces the app data of the live session the token names, written through before the map |
| 522 | /// changes, as a re-challenge records its time. Whether there was a live session. An expired |
| 523 | /// one is left for `check` or the sweep to end; it is not revived. |
| 524 | pub fn set_data( |
| 525 | &self, |
| 526 | db: &(Arc<RwLock<VhostDb>>, Uid), |
| 527 | token: &Token, |
| 528 | data: Dat, |
| 529 | ) |
| 530 | -> Outcome<bool> |
| 531 | { |
| 532 | let now = res!(self.clock.now()); |
| 533 | let hash = res!(token.hash()); |
| 534 | let (db_arc, uid) = db; |
| 535 | let mut state = lock_mutex!(self.state); |
| 536 | let mut e = match state.by_hash.get(&hash) { |
| 537 | Some(e) if !expired(&self.cfg, e, now) => e.clone(), |
| 538 | _ => return Ok(false), |
| 539 | }; |
| 540 | e.data = data; |
| 541 | { |
| 542 | let dbr = lock_read!(db_arc); |
| 543 | res!(dbr.insert(self.cfg.key(&hash), e.to_dat(e.last_seen), uid.clone(), None)); |
| 544 | } |
| 545 | e.stored_seen = e.last_seen; |
| 546 | if let Some(live) = state.by_hash.get_mut(&hash) { |
| 547 | *live = e; |
| 548 | } |
| 549 | debug!("member session: {} data replaced.", short(&hash)); |
| 550 | Ok(true) |
| 551 | } |
| 552 | |
| 553 | /// Ends the session the token names. Whether there was one. |
| 554 | pub fn end( |
| 555 | &self, |
| 556 | db: &(Arc<RwLock<VhostDb>>, Uid), |
| 557 | token: &Token, |
| 558 | ) |
| 559 | -> Outcome<bool> |
| 560 | { |
| 561 | let hash = res!(token.hash()); |
| 562 | self.end_hash(db, &hash) |
| 563 | } |
| 564 | |
| 565 | /// Ends the session with this `Session::id`, for a member who revokes one device from |
| 566 | /// another. Whether there was one. |
| 567 | pub fn end_id( |
| 568 | &self, |
| 569 | db: &(Arc<RwLock<VhostDb>>, Uid), |
| 570 | id: &str, |
| 571 | ) |
| 572 | -> Outcome<bool> |
| 573 | { |
| 574 | match hash_of_key(id) { |
| 575 | Some(hash) => self.end_hash(db, &hash), |
| 576 | None => Ok(false), |
| 577 | } |
| 578 | } |
| 579 | |
| 580 | /// Ends every session of `principal`, and no other. How many there were. |
| 581 | pub fn end_all( |
| 582 | &self, |
| 583 | db: &(Arc<RwLock<VhostDb>>, Uid), |
| 584 | principal: &[u8], |
| 585 | ) |
| 586 | -> Outcome<usize> |
| 587 | { |
| 588 | let (db_arc, uid) = db; |
| 589 | let mut state = lock_mutex!(self.state); |
| 590 | let hashes: Vec<Hash32> = match state.by_principal.get(principal) { |
| 591 | Some(set) => set.iter().map(|(_, h)| *h).collect(), |
| 592 | None => return Ok(0), |
| 593 | }; |
| 594 | let dbr = lock_read!(db_arc); |
| 595 | for hash in &hashes { |
| 596 | // The record goes first: a session the store still held would come back at the |
| 597 | // next load, and a revocation must not be undone by a restart. |
| 598 | res!(dbr.delete(&self.cfg.key(hash), uid.clone(), None)); |
| 599 | state.remove(hash); |
| 600 | } |
| 601 | info!("member session: ended all {} sessions of one principal.", hashes.len()); |
| 602 | Ok(hashes.len()) |
| 603 | } |
| 604 | |
| 605 | /// Ends every expired session. How many. |
| 606 | pub fn sweep(&self, db: &(Arc<RwLock<VhostDb>>, Uid)) -> Outcome<usize> { |
| 607 | let now = res!(self.clock.now()); |
| 608 | let (db_arc, uid) = db; |
| 609 | let mut state = lock_mutex!(self.state); |
| 610 | let gone: Vec<Hash32> = state.by_hash.iter() |
| 611 | .filter(|(_, e)| expired(&self.cfg, e, now)) |
| 612 | .map(|(h, _)| *h) |
| 613 | .collect(); |
| 614 | if gone.is_empty() { |
| 615 | return Ok(0); |
| 616 | } |
| 617 | let dbr = lock_read!(db_arc); |
| 618 | for hash in &gone { |
| 619 | res!(dbr.delete(&self.cfg.key(hash), uid.clone(), None)); |
| 620 | state.remove(hash); |
| 621 | } |
| 622 | debug!("member session: swept {} expired.", gone.len()); |
| 623 | Ok(gone.len()) |
| 624 | } |
| 625 | |
| 626 | /// The live sessions of `principal`, oldest first, as they stand without a touch. |
| 627 | pub fn list(&self, principal: &[u8]) -> Outcome<Vec<Session>> { |
| 628 | let now = res!(self.clock.now()); |
| 629 | let state = lock_mutex!(self.state); |
| 630 | let mut out = Vec::new(); |
| 631 | if let Some(set) = state.by_principal.get(principal) { |
| 632 | for (_, h) in set { |
| 633 | if let Some(e) = state.by_hash.get(h) { |
| 634 | if !expired(&self.cfg, e, now) { |
| 635 | out.push(e.session(h)); |
| 636 | } |
| 637 | } |
| 638 | } |
| 639 | } |
| 640 | Ok(out) |
| 641 | } |
| 642 | |
| 643 | pub fn len(&self) -> Outcome<usize> { |
| 644 | Ok(lock_mutex!(self.state).by_hash.len()) |
| 645 | } |
| 646 | |
| 647 | fn end_hash( |
| 648 | &self, |
| 649 | db: &(Arc<RwLock<VhostDb>>, Uid), |
| 650 | hash: &Hash32, |
| 651 | ) |
| 652 | -> Outcome<bool> |
| 653 | { |
| 654 | let (db_arc, uid) = db; |
| 655 | let mut state = lock_mutex!(self.state); |
| 656 | if !state.by_hash.contains_key(hash) { |
| 657 | return Ok(false); |
| 658 | } |
| 659 | let dbr = lock_read!(db_arc); |
| 660 | // The record first, as in `end_all`: if it cannot be deleted the session stays live and |
| 661 | // the caller is told, rather than its coming back at the next restart. |
| 662 | res!(dbr.delete(&self.cfg.key(hash), uid.clone(), None)); |
| 663 | state.remove(hash); |
| 664 | debug!("member session: {} ended.", short(hash)); |
| 665 | Ok(true) |
| 666 | } |
| 667 | } |
| 668 | |
| 669 | fn expired(cfg: &SessionCfg, e: &Entry, now: u64) -> bool { |
| 670 | now >= e.last_seen.saturating_add(cfg.idle_secs) |
| 671 | || now >= e.created.saturating_add(cfg.absolute_secs) |
| 672 | } |