ext/web W1–W3: middleware, data layer, and security hardening

Deliver the interrupted network extension backlog: declarative middleware
(CORS, security headers, gzip, JSON API), SQLite pool/transactions/pagination,
and W3 security (argon2 passwords, CSRF on forms/login, persistent sessions,
CSPRNG ids, login rate limiting). Adds gold smokes and author-facing
hash_password on ext/web.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
cflmyandCursor committed 2026-08-28 09:35:39 +08:00
1 parent da9fc75b1e
commit be6223f1fb
22 files changed
+3081 -343

No files matched your search

+372 -127
View File
@@ -1,22 +1,40 @@
//! In-memory session store + cookie helpers (design ext-web-net §3.1 / §3.2).
//! Session store + cookie helpers + CSRF tokens (ext-web-net W3).
//!
//! Sessions live for the lifetime of the plugin process (same as `web_listen`).
//! Session ids are random hex strings; cookies are `marqdo_sid=<id>` with
//! `HttpOnly; Path=/; SameSite=Lax`.
//! - **CSPRNG** session ids (`getrandom`).
//! - **SQLite persistence** when `configure` receives a `db_url`; otherwise in-memory (offline gold).
//! - **Sliding expiry** on read/write.
//! - **CSRF** token per session (`_csrf` key).
use std::collections::HashMap;
use std::sync::Mutex;
use std::time::{SystemTime, UNIX_EPOCH};
use getrandom::getrandom;
use serde_json::{json, Map, Value};
use crate::db;
use crate::password;
type SessionMap = HashMap<String, Value>;
struct Store {
#[derive(Clone, Default)]
pub struct Config {
pub db_url: Option<String>,
pub ttl_sec: u64,
pub cookie_secure: bool,
}
static CONFIG: Mutex<Option<Config>> = Mutex::new(None);
struct MemStore {
ttl_sec: u64,
data: HashMap<String, (u64, SessionMap)>,
}
static STORE: Mutex<Option<Store>> = Mutex::new(None);
static MEM: Mutex<Option<MemStore>> = Mutex::new(None);
const SESSION_TABLE: &str = "_marqdo_sessions";
const CSRF_KEY: &str = "_csrf";
fn now_secs() -> u64 {
SystemTime::now()
@@ -25,111 +43,310 @@ fn now_secs() -> u64 {
.unwrap_or(0)
}
fn with_store<T>(f: impl FnOnce(&mut Store) -> T) -> T {
let mut guard = STORE.lock().unwrap_or_else(|e| e.into_inner());
let store = guard.get_or_insert_with(|| Store {
ttl_sec: 3600,
fn cfg() -> Config {
CONFIG
.lock()
.unwrap_or_else(|e| e.into_inner())
.clone()
.unwrap_or(Config {
db_url: None,
ttl_sec: 3600,
cookie_secure: false,
})
}
/// Configure session backend before `listen` or offline ABI calls.
pub fn configure(config: Config) {
let ttl = if config.ttl_sec > 0 {
config.ttl_sec
} else {
3600
};
let mut c = config;
c.ttl_sec = ttl;
if let Some(ref url) = c.db_url {
let _ = ensure_session_table(url);
}
let mut guard = CONFIG.lock().unwrap_or_else(|e| e.into_inner());
*guard = Some(c);
}
/// Reset in-memory sessions (tests / each listen).
pub fn reset(ttl_sec: u64) {
let ttl = if ttl_sec > 0 { ttl_sec } else { 3600 };
{
let mut guard = CONFIG.lock().unwrap_or_else(|e| e.into_inner());
if let Some(ref mut c) = *guard {
c.ttl_sec = ttl;
} else {
*guard = Some(Config {
db_url: None,
ttl_sec: ttl,
cookie_secure: false,
});
}
}
let mut mem = MEM.lock().unwrap_or_else(|e| e.into_inner());
*mem = Some(MemStore {
ttl_sec: ttl,
data: HashMap::new(),
});
}
fn ensure_session_table(url: &str) -> Result<(), String> {
db::exec(
url,
&format!(
"CREATE TABLE IF NOT EXISTS \"{SESSION_TABLE}\" (
id TEXT PRIMARY KEY,
expires_at INTEGER NOT NULL,
data TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_marqdo_sessions_exp ON \"{SESSION_TABLE}\"(expires_at);"
),
None,
None,
)?;
Ok(())
}
fn prune_mem(store: &mut MemStore) {
let now = now_secs();
store.data.retain(|_, (exp, _)| *exp > now);
}
fn prune_sql(url: &str) {
let now = now_secs() as i64;
let _ = db::exec(
url,
&format!("DELETE FROM \"{SESSION_TABLE}\" WHERE expires_at <= ?1"),
Some(&json!([now])),
None,
);
}
fn secure_random_id() -> Result<String, String> {
let mut bytes = [0u8; 32];
getrandom(&mut bytes).map_err(|e| format!("getrandom: {e}"))?;
Ok(bytes.iter().map(|b| format!("{b:02x}")).collect())
}
fn random_csrf() -> Result<String, String> {
let mut bytes = [0u8; 24];
getrandom(&mut bytes).map_err(|e| format!("getrandom: {e}"))?;
Ok(bytes.iter().map(|b| format!("{b:02x}")).collect())
}
fn map_to_json(m: &SessionMap) -> Result<String, String> {
let obj: Map<String, Value> = m.iter().map(|(k, v)| (k.clone(), v.clone())).collect();
serde_json::to_string(&Value::Object(obj)).map_err(|e| e.to_string())
}
fn json_to_map(s: &str) -> SessionMap {
match serde_json::from_str::<Value>(s) {
Ok(Value::Object(m)) => m.into_iter().collect(),
_ => HashMap::new(),
}
}
fn load_sql(url: &str, id: &str) -> Option<(u64, SessionMap)> {
let q = db::query(
url,
&format!("SELECT expires_at, data FROM \"{SESSION_TABLE}\" WHERE id = ?1"),
Some(&json!([id])),
None,
)
.ok()?;
let rows = q.get("rows")?.as_array()?;
let row = rows.first()?;
let exp = row.get("expires_at")?.as_i64()? as u64;
let data_s = row.get("data")?.as_str()?;
Some((exp, json_to_map(data_s)))
}
fn save_sql(url: &str, id: &str, exp: u64, data: &SessionMap) -> Result<(), String> {
let data_s = map_to_json(data)?;
db::exec(
url,
&format!(
"INSERT INTO \"{SESSION_TABLE}\" (id, expires_at, data) VALUES (?1, ?2, ?3)
ON CONFLICT(id) DO UPDATE SET expires_at = excluded.expires_at, data = excluded.data"
),
Some(&json!([id, exp as i64, data_s])),
None,
)?;
Ok(())
}
fn delete_sql(url: &str, id: &str) {
let _ = db::exec(
url,
&format!("DELETE FROM \"{SESSION_TABLE}\" WHERE id = ?1"),
Some(&json!([id])),
None,
);
}
fn touch_expiry(ttl: u64) -> u64 {
now_secs() + ttl
}
fn ensure_csrf(data: &mut SessionMap) -> Result<String, String> {
if let Some(Value::String(t)) = data.get(CSRF_KEY) {
if !t.is_empty() {
return Ok(t.clone());
}
}
let t = random_csrf()?;
data.insert(CSRF_KEY.to_string(), json!(t));
Ok(t)
}
pub fn session_new(ttl_sec: Option<u64>) -> String {
let cfg = cfg();
let ttl = ttl_sec.unwrap_or(cfg.ttl_sec);
if ttl > 0 {
if let Ok(mut guard) = CONFIG.lock() {
if let Some(ref mut c) = *guard {
c.ttl_sec = ttl;
}
}
}
let id = secure_random_id().unwrap_or_else(|_| format!("fallback-{}", now_secs()));
let exp = touch_expiry(ttl);
let mut data = SessionMap::new();
let _ = ensure_csrf(&mut data);
if let Some(ref url) = cfg.db_url {
prune_sql(url);
let _ = save_sql(url, &id, exp, &data);
} else {
with_mem(|store| {
store.ttl_sec = ttl;
prune_mem(store);
store.data.insert(id.clone(), (exp, data));
});
}
id
}
fn with_mem<T>(f: impl FnOnce(&mut MemStore) -> T) -> T {
let mut guard = MEM.lock().unwrap_or_else(|e| e.into_inner());
let store = guard.get_or_insert_with(|| MemStore {
ttl_sec: cfg().ttl_sec,
data: HashMap::new(),
});
f(store)
}
fn prune(store: &mut Store) {
fn get_record(id: &str) -> Option<(u64, SessionMap)> {
let cfg = cfg();
let now = now_secs();
store.data.retain(|_, (exp, _)| *exp > now);
}
fn random_id() -> String {
use std::time::{SystemTime, UNIX_EPOCH};
let nanos = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.subsec_nanos())
.unwrap_or(0);
let pid = std::process::id();
// Cheap but adequate unique-enough id for an in-memory session store.
format!("{pid:x}{nanos:x}{:x}", rand_word())
}
fn rand_word() -> u64 {
// xorshift64 from a counter; not cryptographically strong but fine for
// session cookies when combined with pid+time. (Plugin is single-process.)
static COUNTER: Mutex<u64> = Mutex::new(0x9e3779b97f4a7c15);
let mut c = COUNTER.lock().unwrap_or_else(|e| e.into_inner());
let mut x = *c;
x ^= x << 13;
x ^= x >> 7;
x ^= x << 17;
*c = x;
x
}
/// Reset the store (used between listens / for tests).
pub fn reset(ttl_sec: u64) {
let mut guard = STORE.lock().unwrap_or_else(|e| e.into_inner());
*guard = Some(Store {
ttl_sec,
data: HashMap::new(),
});
}
pub fn session_new(ttl_sec: Option<u64>) -> String {
with_store(|store| {
if let Some(ttl) = ttl_sec {
if ttl > 0 {
store.ttl_sec = ttl;
}
if let Some(ref url) = cfg.db_url {
prune_sql(url);
let (exp, data) = load_sql(url, id)?;
if exp <= now {
delete_sql(url, id);
return None;
}
prune(store);
let id = random_id();
let exp = now_secs() + store.ttl_sec;
store.data.insert(id.clone(), (exp, SessionMap::new()));
id
})
Some((exp, data))
} else {
with_mem(|store| {
prune_mem(store);
let (exp, data) = store.data.get(id)?.clone();
if exp <= now {
store.data.remove(id);
return None;
}
Some((exp, data))
})
}
}
fn put_record(id: &str, exp: u64, data: SessionMap) -> bool {
let cfg = cfg();
if let Some(ref url) = cfg.db_url {
save_sql(url, id, exp, &data).is_ok()
} else {
with_mem(|store| {
store.data.insert(id.to_string(), (exp, data));
true
})
}
}
pub fn session_set(id: &str, key: &str, value: Value) -> bool {
with_store(|store| {
prune(store);
let Some((exp, m)) = store.data.get_mut(id) else {
return false;
};
if *exp <= now_secs() {
return false;
}
m.insert(key.to_string(), value);
true
})
let cfg = cfg();
let Some((_, mut data)) = get_record(id) else {
return false;
};
data.insert(key.to_string(), value);
put_record(id, touch_expiry(cfg.ttl_sec), data)
}
pub fn session_get(id: &str, key: &str) -> Option<Value> {
with_store(|store| {
prune(store);
let (exp, m) = store.data.get(id)?;
if *exp <= now_secs() {
return None;
}
m.get(key).cloned()
})
let cfg = cfg();
let (_, data) = get_record(id)?;
let v = data.get(key).cloned()?;
put_record(id, touch_expiry(cfg.ttl_sec), data);
Some(v)
}
pub fn session_del(id: &str, key: &str) -> bool {
with_store(|store| {
prune(store);
let Some((exp, m)) = store.data.get_mut(id) else {
return false;
};
if *exp <= now_secs() {
return false;
}
m.remove(key).is_some()
})
let cfg = cfg();
let Some((_, mut data)) = get_record(id) else {
return false;
};
let ok = data.remove(key).is_some();
if ok {
put_record(id, touch_expiry(cfg.ttl_sec), data);
}
ok
}
pub fn session_destroy(id: &str) -> bool {
with_store(|store| {
prune(store);
store.data.remove(id).is_some()
})
let cfg = cfg();
if let Some(ref url) = cfg.db_url {
delete_sql(url, id);
true
} else {
with_mem(|store| store.data.remove(id).is_some())
}
}
/// CSRF token for an existing session (creates one if missing).
pub fn csrf_for(id: &str) -> Option<String> {
let cfg = cfg();
let (_, mut data) = get_record(id)?;
let token = ensure_csrf(&mut data).ok()?;
put_record(id, touch_expiry(cfg.ttl_sec), data);
Some(token)
}
pub fn validate_csrf(id: &str, token: &str) -> bool {
if token.is_empty() {
return false;
}
match session_get(id, CSRF_KEY) {
Some(Value::String(stored)) => stored == token,
_ => false,
}
}
/// Resolve session from cookie: reuse valid id or create a new one.
/// Returns `(session_id, set_cookie_header)`.
pub fn ensure_from_cookie(cookie_header: Option<&str>) -> (String, Option<String>) {
if let Some(id) = session_id_from_cookie(cookie_header) {
if get_record(&id).is_some() {
let _ = csrf_for(&id);
return (id, None);
}
}
let id = session_new(None);
let cfg = cfg();
(
id.clone(),
Some(session_cookie(&id, cfg.ttl_sec, cfg.cookie_secure)),
)
}
/// Parse the session id from a `Cookie` request header (looks for `marqdo_sid=…`).
@@ -147,16 +364,18 @@ pub fn session_id_from_cookie(cookie_header: Option<&str>) -> Option<String> {
None
}
/// `Set-Cookie: marqdo_sid=<id>; HttpOnly; Path=/; SameSite=Lax; Max-Age=<ttl>`
pub fn session_cookie(id: &str, ttl_sec: u64) -> String {
format!(
/// `Set-Cookie: marqdo_sid=<id>; HttpOnly; Path=/; SameSite=Lax; Max-Age=<ttl>[; Secure]`
pub fn session_cookie(id: &str, ttl_sec: u64, secure: bool) -> String {
let mut s = format!(
"marqdo_sid={id}; HttpOnly; Path=/; SameSite=Lax; Max-Age={ttl_sec}"
)
);
if secure {
s.push_str("; Secure");
}
s
}
/// Validate `username`/`password` against an admin-users table (`|用户名|密码|`
/// with headers `username`/`密码` or `用户`/`密码`, or plain `username`/`password`).
/// Returns the matched username on success.
/// Validate credentials; supports argon2 hashes or legacy plaintext in the password column.
pub fn check_credentials(users: &Value, username: &str, password: &str) -> Option<String> {
let rows = match users {
Value::Array(a) => a,
@@ -173,7 +392,7 @@ pub fn check_credentials(users: &Value, username: &str, password: &str) -> Optio
let p = pick_cell(m, &["密码", "password", "pass", "口令"])
.map(cell_str)
.unwrap_or_default();
if u == username && p == password {
if u == username && password::verify_password(password, &p) {
return Some(u);
}
}
@@ -194,7 +413,6 @@ fn cell_str(v: &Value) -> String {
}
}
/// ABI helpers.
pub fn abi_session_new(args: &Value) -> Result<Value, String> {
let ttl = args
.get("ttl_sec")
@@ -260,6 +478,12 @@ pub fn abi_auth_logout(args: &Value) -> Result<Value, String> {
Ok(json!({ "ok": session_destroy(id) }))
}
pub fn abi_password_hash(args: &Value) -> Result<Value, String> {
let plain = arg_str(args, "password")?;
let hash = password::hash_password(plain)?;
Ok(json!({ "hash": hash }))
}
fn arg_str<'a>(v: &'a Value, key: &str) -> Result<&'a str, String> {
v.get(key)
.and_then(|x| x.as_str())
@@ -283,10 +507,7 @@ mod tests {
let id = session_new(None);
assert!(!id.is_empty());
assert!(session_set(&id, "username", json!("admin")));
assert_eq!(
session_get(&id, "username"),
Some(json!("admin"))
);
assert_eq!(session_get(&id, "username"), Some(json!("admin")));
assert!(session_del(&id, "username"));
assert_eq!(session_get(&id, "username"), None);
assert!(session_destroy(&id));
@@ -305,7 +526,6 @@ mod tests {
let sid = r["session_id"].as_str().unwrap().to_string();
let check = abi_auth_check(&json!({ "session_id": sid })).unwrap();
assert_eq!(check["ok"].as_bool(), Some(true));
assert_eq!(check["username"], "admin");
let bad = abi_auth_login(&json!({
"username": "admin",
@@ -315,39 +535,64 @@ mod tests {
.unwrap();
assert_eq!(bad["ok"].as_bool(), Some(false));
// Chinese column headers also work.
let zh = abi_auth_login(&json!({
"username": "站长",
"password": "pw123",
"users": users(),
}))
.unwrap();
assert_eq!(zh["ok"].as_bool(), Some(true));
let out = abi_auth_logout(&json!({ "session_id": sid })).unwrap();
assert_eq!(out["ok"].as_bool(), Some(true));
let check2 = abi_auth_check(&json!({ "session_id": sid })).unwrap();
assert_eq!(check2["ok"].as_bool(), Some(false));
}
#[test]
fn csrf_roundtrip() {
reset(3600);
let id = session_new(None);
let t = csrf_for(&id).unwrap();
assert!(validate_csrf(&id, &t));
assert!(!validate_csrf(&id, "bad"));
}
#[test]
fn cookie_roundtrip() {
reset(3600);
let id = session_new(None);
let cookie = session_cookie(&id, 3600);
let cookie = session_cookie(&id, 3600, false);
assert!(cookie.starts_with("marqdo_sid="));
let got = session_id_from_cookie(Some(&format!(
"theme=light; {cookie}"
)));
let got = session_id_from_cookie(Some(&format!("theme=light; {cookie}")));
assert_eq!(got.as_deref(), Some(id.as_str()));
assert_eq!(session_id_from_cookie(Some("theme=light")), None);
assert_eq!(session_id_from_cookie(None), None);
}
#[test]
fn check_credentials_missing() {
assert!(check_credentials(&json!(null), "a", "b").is_none());
assert!(check_credentials(&json!("x"), "a", "b").is_none());
assert!(check_credentials(&json!([]), "a", "b").is_none());
fn hashed_password_login() {
reset(3600);
let hash = password::hash_password("secret").unwrap();
let users = json!([{ "username": "admin", "password": hash }]);
let r = abi_auth_login(&json!({
"username": "admin",
"password": "secret",
"users": users,
}))
.unwrap();
assert_eq!(r["ok"].as_bool(), Some(true));
}
#[test]
fn session_persists_in_sqlite() {
let dir = std::env::temp_dir().join(format!("marqdo_web_sess_{}", std::process::id()));
let _ = std::fs::create_dir_all(&dir);
let path = dir.join("persist.db");
let _ = std::fs::remove_file(&path);
let url = format!("sqlite:{}", path.display());
configure(Config {
db_url: Some(url.clone()),
ttl_sec: 3600,
cookie_secure: false,
});
let id = session_new(None);
assert!(session_set(&id, "theme", json!("dark")));
// Re-configure (simulates listen restart with same db).
configure(Config {
db_url: Some(url),
ttl_sec: 3600,
cookie_secure: false,
});
assert_eq!(session_get(&id, "theme"), Some(json!("dark")));
let _ = std::fs::remove_dir_all(dir);
}
}