From 8bedae5aafc09165e39500aecf5433c62b54c212 Mon Sep 17 00:00:00 2001 From: admin Date: Sat, 24 Oct 2026 16:33:44 +0800 Subject: [PATCH] =?UTF-8?q?feat(auth):=20=E8=BF=9E=E6=8E=A5=E5=99=A8?= =?UTF-8?q?=E4=BC=9A=E8=AF=9D=E5=AD=98=E5=82=A8=EF=BC=88=E5=86=85=E5=AD=98?= =?UTF-8?q?=20/=2030=20=E5=88=86=E9=92=9F=20TTL=20/=2032=20=E4=BD=8D?= =?UTF-8?q?=E5=8D=81=E5=85=AD=E8=BF=9B=E5=88=B6=20token=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Code --- src/lib.rs | 1 + src/session.rs | 156 +++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 157 insertions(+) create mode 100644 src/session.rs diff --git a/src/lib.rs b/src/lib.rs index 6663d4b..20f280e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -12,3 +12,4 @@ pub mod db; pub mod envelope; pub mod ids; pub mod protocol; +pub mod session; diff --git a/src/session.rs b/src/session.rs new file mode 100644 index 0000000..8f89bb1 --- /dev/null +++ b/src/session.rs @@ -0,0 +1,156 @@ +//! 连接器前端会话:内存、30 分钟 TTL、进程重启即失效。 +//! +//! 上游等价物:`ssw/tdc/support/TdcSessionStore` +//! (token = 去掉连字符的 UUID,TTL `30L*60*1000` ms,内存 `ConcurrentHashMap`)。 + +use std::collections::HashMap; +use std::sync::{Mutex, MutexGuard}; +use std::time::{Duration, Instant}; + +use rand::RngCore; + +/// 会话有效期:30 分钟。 +pub const SESSION_TTL: Duration = Duration::from_secs(30 * 60); + +/// 会话主体。 +#[derive(Clone, Debug)] +pub struct Session { + pub kind: SessionKind, + pub identity_id: String, + pub identity_code: String, + pub expire_at: Instant, +} + +/// 会话主体种类。 +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum SessionKind { + /// 连接器身份会话(`identityCode` + `secretKey` 登录)。 + Identity, + /// 本地账号会话(控制台账号 + 口令登录)。 + Account, +} + +/// 内存会话表。 +pub struct SessionStore { + inner: Mutex>, +} + +impl Default for SessionStore { + fn default() -> Self { + Self::new() + } +} + +impl SessionStore { + pub fn new() -> Self { + Self { inner: Mutex::new(HashMap::new()) } + } + + /// 签发 token:32 位十六进制(上游是去掉连字符的 UUID)。 + pub fn create(&self, identity_id: &str, identity_code: &str) -> String { + self.create_with_kind(SessionKind::Identity, identity_id, identity_code) + } + + /// 签发**本地账号**会话 token(控制台账号口令登录)。 + pub fn create_account(&self, account_id: &str, account: &str) -> String { + self.create_with_kind(SessionKind::Account, account_id, account) + } + + fn create_with_kind(&self, kind: SessionKind, subject_id: &str, subject_code: &str) -> String { + let mut bytes = [0u8; 16]; + rand::rngs::OsRng.fill_bytes(&mut bytes); + let token = hex::encode(bytes); + let session = Session { + kind, + identity_id: subject_id.to_string(), + identity_code: subject_code.to_string(), + expire_at: Instant::now() + SESSION_TTL, + }; + self.lock().insert(token.clone(), session); + token + } + + /// 取会话;过期即删除并返回 `None`。 + pub fn lookup(&self, token: &str) -> Option { + let mut map = self.lock(); + match map.get(token) { + Some(s) if s.expire_at > Instant::now() => Some(s.clone()), + Some(_) => { + map.remove(token); + None + } + None => None, + } + } + + /// 吊销会话;返回是否确实删掉了一条。 + pub fn revoke(&self, token: &str) -> bool { + self.lock().remove(token).is_some() + } + + fn lock(&self) -> MutexGuard<'_, HashMap> { + self.inner.lock().unwrap_or_else(|e| e.into_inner()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn created_token_is_32_hex_chars_without_dashes() { + let store = SessionStore::new(); + let token = store.create("id-1", "LOCAL-CONNECTOR"); + assert_eq!(token.len(), 32, "上游是去掉连字符的 UUID:{}", token); + assert!(token.chars().all(|c| c.is_ascii_hexdigit()), "token 应为十六进制:{}", token); + assert!(!token.contains('-')); + } + + #[test] + fn lookup_returns_the_identity_and_rejects_unknown_tokens() { + let store = SessionStore::new(); + let token = store.create("id-1", "LOCAL-CONNECTOR"); + let s = store.lookup(&token).expect("会话应有效"); + assert_eq!(s.identity_id, "id-1"); + assert_eq!(s.identity_code, "LOCAL-CONNECTOR"); + assert!(store.lookup("deadbeef").is_none()); + } + + #[test] + fn expired_session_is_rejected() { + let store = SessionStore::new(); + let token = store.create("id-1", "CODE"); + // 人为把过期时间改到过去 + { + let mut map = store.lock(); + if let Some(s) = map.get_mut(&token) { + s.expire_at = Instant::now() - Duration::from_secs(1); + } + } + assert!(store.lookup(&token).is_none(), "过期会话必须被拒"); + } + + #[test] + fn revoke_removes_the_session() { + let store = SessionStore::new(); + let token = store.create("id-1", "CODE"); + assert!(store.revoke(&token)); + assert!(store.lookup(&token).is_none()); + } + + #[test] + fn ttl_is_thirty_minutes() { + assert_eq!(SESSION_TTL, Duration::from_secs(1800)); + } + + #[test] + fn account_sessions_are_distinguishable_from_identity_sessions() { + let store = SessionStore::new(); + let id_token = store.create("id-1", "LOCAL-CONNECTOR"); + let acc_token = store.create_account("u-1", "admin"); + assert_eq!(store.lookup(&id_token).unwrap().kind, SessionKind::Identity); + assert_eq!(store.lookup(&acc_token).unwrap().kind, SessionKind::Account); + assert_eq!(store.lookup(&acc_token).unwrap().identity_id, "u-1"); + assert_eq!(store.lookup(&acc_token).unwrap().identity_code, "admin"); + } +}