feat(auth): 连接器会话存储(内存 / 30 分钟 TTL / 32 位十六进制 token)
Co-Authored-By: Claude Code <[email protected]>
This commit is contained in:
1 parent
5069c552de
commit
8bedae5aaf
2 files changed
+157
No files matched your search
@@ -12,3 +12,4 @@ pub mod db;
|
||||
pub mod envelope;
|
||||
pub mod ids;
|
||||
pub mod protocol;
|
||||
pub mod session;
|
||||
+156
@@ -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<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 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");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user