复审指出的两个测试覆盖盲区(实现本身无误,仅补测试): - session_expire_at_is_anchored_to_session_ttl:从内部 map 直接读出会话的 expire_at,断言其落在 now + SESSION_TTL ±1 秒窗口内。此前把 expire_at 改成 now + 3600s 六个测试全绿,会话时长可静默漂移。 - revoke_returns_false_for_unknown_token:断言吊销从未签发的 token 返回 false,且同一 token 二次吊销也返回 false。此前 revoke 恒返回 true 也全绿。 未改动实现、未改动既有六个测试。 Co-Authored-By: Claude Code <[email protected]>
188 lines
6.2 KiB
Rust
188 lines
6.2 KiB
Rust
//! 连接器前端会话:内存、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<HashMap<String, Session>>,
|
||
}
|
||
|
||
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<Session> {
|
||
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<String, Session>> {
|
||
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 session_expire_at_is_anchored_to_session_ttl() {
|
||
let store = SessionStore::new();
|
||
let before = Instant::now();
|
||
let token = store.create("id-1", "CODE");
|
||
let after = Instant::now();
|
||
let expire_at = {
|
||
let map = store.lock();
|
||
map.get(&token).expect("会话应存在").expire_at
|
||
};
|
||
// 容差 ±1 秒,覆盖容器/机器调度抖动;不做纳秒级等值断言。
|
||
let lower = before + SESSION_TTL - Duration::from_secs(1);
|
||
let upper = after + SESSION_TTL + Duration::from_secs(1);
|
||
assert!(
|
||
expire_at >= lower && expire_at <= upper,
|
||
"会话过期时间应锚定在 now + SESSION_TTL 附近(实际 {:?},期望区间 [{:?}, {:?}])",
|
||
expire_at,
|
||
lower,
|
||
upper
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn revoke_returns_false_for_unknown_token() {
|
||
let store = SessionStore::new();
|
||
assert!(!store.revoke("never-issued-token"), "未签发的 token 不得报告吊销成功");
|
||
let token = store.create("id-1", "CODE");
|
||
assert!(store.revoke(&token));
|
||
assert!(!store.revoke(&token), "已吊销的 token 再次吊销不得报告成功");
|
||
}
|
||
|
||
#[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");
|
||
}
|
||
}
|