Files
ssw__ipass/rust/src/domains.rs
T
admin 5c307ba1aa iPass 山海关:Rust 动态模块版全量入库
- vanilla nginx + Rust 动态模块(取代 OpenResty+Lua),共享内存为运行期真源
- 三域名分流 18098 ssl:mdm 管理台 / lm LLM 代理 / *.dm 企业转发,共用 *.mayishangshu.cn 通配符证书(证书不入库)
- LLM 统一出口:同 Key 鉴权、上游 Key 替换、白名单、限流配额、SSE
- 回归夹具 tests/(网关 55 + LLM 34 = 89 断言,夹具 cp 覆盖重置)
- 文档:readme(16 章)+ CLAUDE.md + conf/tls/README(acme.sh 证书管理、hairpin 环回链路)
2026-09-11 15:37:09 +08:00

407 lines
14 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! 域名(子域名映射)与申请审核。
//!
//! 对应旧版 `lua/domains.lua`。数据结构见 `models::DomainEntry`。
//!
//! ## 状态机
//!
//! ```text
//! temp + 有临时授权权限 → 直接 approved(reviewed_by=auto,到时自动 expired)
//! temp + 无临时授权权限 → pending,等管理员审核
//! long + 任意 → pending,等管理员审核
//! ```
//!
//! 到期不等于删除:临时域名过期后仅「不再转发」,记录保留供查阅。
//!
//! ## 与旧版最大的差异:写穿
//!
//! 旧版写操作后 `invalidate` 掉缓存,靠「未命中回源读文件」拿到新值;
//! 新版热路径**永不回源**(未命中即 404),所以每个写操作都必须
//! **同时更新共享内存与文件**——这就是 `sync_shm` 的存在理由。
//! 漏掉一处,就会出现「审核通过了但立刻 404」。
use serde_json::{Value, json};
use crate::config::{
KEY_SUB_PREFIX, REJECTED_PURGE_TTL, RESERVED_SUBDOMAINS, SUBDOMAIN_MAX_LEN, TEMP_DOMAIN_TTL,
};
use crate::models::DomainEntry;
use crate::state;
use crate::store;
use crate::util;
// ===========================================================================
// 校验
// ===========================================================================
/// 子域名:小写字母/数字开头,其后可含短横线,总长 ≤ 62,且不在保留名单内。
/// 返回规范化(小写)后的值。
pub fn validate_subdomain(raw: &str) -> Result<String, String> {
if raw.is_empty() {
return Err("缺少 subdomain 参数".to_owned());
}
let s = raw.to_ascii_lowercase();
let bytes = s.as_bytes();
if bytes.len() > SUBDOMAIN_MAX_LEN {
return Err("子域名长度不能超过 62 个字符".to_owned());
}
let head_ok = matches!(bytes[0], b'a'..=b'z' | b'0'..=b'9');
let tail_ok = bytes[1..].iter().all(|&b| matches!(b, b'a'..=b'z' | b'0'..=b'9' | b'-'));
if !head_ok || !tail_ok {
return Err("子域名只能是小写字母、数字、短横线,且不能以短横线开头".to_owned());
}
if RESERVED_SUBDOMAINS.contains(&s.as_str()) {
return Err(format!("子域名 {s} 为系统保留名,不可使用"));
}
Ok(s)
}
/// 后端地址:`host:port`,host 允许字母/数字/`.`/`_`/`-`,端口 1-65535
pub fn validate_backend(raw: &str) -> Result<String, String> {
let s = util::trim(raw);
if s.is_empty() {
return Err("缺少 backend 参数".to_owned());
}
let Some(colon) = s.rfind(':') else {
return Err("backend 格式应为 host:port,例如 192.168.1.7:89".to_owned());
};
let (host, port) = (&s[..colon], &s[colon + 1..]);
let host_ok = !host.is_empty()
&& host.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'));
let port_ok = !port.is_empty()
&& port.chars().all(|c| c.is_ascii_digit())
&& port.parse::<u32>().map(|p| (1..=65535).contains(&p)).unwrap_or(false);
if !host_ok || !port_ok {
return Err("backend 格式应为 host:port,且端口在 1-65535 之间".to_owned());
}
Ok(s.to_owned())
}
pub fn validate_type(raw: Option<&String>) -> String {
match raw.map(|s| s.as_str()) {
Some("long") => "long".to_owned(),
_ => "temp".to_owned(),
}
}
// ===========================================================================
// 共享内存同步(写穿 / 装载)
// ===========================================================================
/// 把一条记录同步进共享内存。**所有写操作之后必须调用它**。
pub fn sync_shm(entry: &DomainEntry) {
let now = util::now();
if entry.is_forwardable(now) {
// long 用 0 表示永不过期;temp 用真实到期时刻,热路径读到即知是否还能用
let exp = if entry.dtype == "temp" { entry.expires_at } else { 0 };
state::put_backend(entry.subdomain.as_bytes(), entry.backend.as_bytes(), exp);
} else {
state::invalidate(entry.subdomain.as_bytes());
}
}
/// 全量重载转发映射(启动装载 / purge / 连带回收后调用)。返回装载条数。
///
/// 只清 `sub:` 前缀的键,**不会误伤正在登录的管理员会话**。
pub fn reload_shm() -> usize {
state::clear_prefix(KEY_SUB_PREFIX);
let now = util::now();
let mut loaded = 0;
for entry in store::read_domains() {
if entry.is_forwardable(now) {
let exp = if entry.dtype == "temp" { entry.expires_at } else { 0 };
if state::put_backend(entry.subdomain.as_bytes(), entry.backend.as_bytes(), exp) {
loaded += 1;
}
}
}
loaded
}
// ===========================================================================
// 查询
// ===========================================================================
/// 全部记录,按创建时间倒序
pub fn all() -> Vec<DomainEntry> {
let mut list = store::read_domains();
list.sort_by(|a, b| b.created_at.cmp(&a.created_at));
list
}
pub fn by_owner(owner: &str) -> Vec<DomainEntry> {
let mut list: Vec<DomainEntry> =
store::read_domains().into_iter().filter(|e| e.owner == owner).collect();
list.sort_by(|a, b| b.created_at.cmp(&a.created_at));
list
}
/// 按 id 取单条记录(当前无调用方,保留为对外查询接口)
#[allow(dead_code)]
pub fn by_id(id: &str) -> Option<DomainEntry> {
store::read_domains().into_iter().find(|e| e.id == id)
}
pub fn count_pending() -> usize {
store::read_domains().iter().filter(|e| e.status == "pending").count()
}
// ===========================================================================
// 用户申请
// ===========================================================================
/// 用户提交申请。有临时授权权限的 temp 申请直接放行。
///
/// 返回的 entry 若 `status == approved && reviewed_by == auto`,即免审通过。
pub fn apply(
username: &str,
subdomain: &str,
backend: &str,
dtype: Option<&String>,
) -> Result<DomainEntry, String> {
let user = crate::users::get(username).ok_or("账号不存在")?;
let subdomain = validate_subdomain(subdomain)?;
let backend = validate_backend(backend)?;
let dtype = validate_type(dtype);
let now = util::now();
let auto = dtype == "temp" && user.has_temp_permission(now);
let chosen = subdomain.clone();
let entry = store::update_domains(move |list| {
if let Some(idx) = list.iter().position(|e| e.subdomain == chosen) {
let existing = &list[idx];
let mine_pending = existing.owner == username && existing.status == "pending";
let its_expired =
existing.dtype == "temp" && existing.effective_status(now) == "expired";
// 自己的待审申请可以改写;已失效的临时域名视为空闲可复用
if !(mine_pending || its_expired) {
return Err(format!("子域名 {chosen} 已被占用"));
}
list.remove(idx);
}
let entry = DomainEntry {
id: util::gen_id(),
subdomain: chosen,
backend,
dtype,
owner: username.to_owned(),
status: if auto { "approved".to_owned() } else { "pending".to_owned() },
created_at: now,
expires_at: if auto { now + TEMP_DOMAIN_TTL } else { 0 },
reviewed_by: if auto { "auto".to_owned() } else { String::new() },
reviewed_at: if auto { now } else { 0 },
};
list.push(entry.clone());
Ok(entry)
})?;
sync_shm(&entry);
Ok(entry)
}
// ===========================================================================
// 管理员操作
// ===========================================================================
/// 审核:approve / reject。只允许处理 pending 状态。
pub fn review(id: &str, action: &str, admin: &str) -> Result<DomainEntry, String> {
if action != "approve" && action != "reject" {
return Err("action 只能是 approve 或 reject".to_owned());
}
let now = util::now();
let id = id.to_owned();
let action = action.to_owned();
let admin = admin.to_owned();
let updated = store::update_domains(move |list| {
let item = list.iter_mut().find(|e| e.id == id).ok_or("记录不存在")?;
if item.status != "pending" {
return Err(format!("该申请已处理(当前状态:{})", item.status));
}
if action == "approve" {
item.status = "approved".to_owned();
item.expires_at = if item.dtype == "temp" { now + TEMP_DOMAIN_TTL } else { 0 };
} else {
item.status = "rejected".to_owned();
}
item.reviewed_by = admin;
item.reviewed_at = now;
Ok(item.clone())
})?;
sync_shm(&updated);
Ok(updated)
}
/// 管理员直接创建并放行(等价于「我替你建好并批准」)
pub fn create_by_admin(
subdomain: &str,
backend: &str,
dtype: Option<&String>,
owner: Option<&String>,
admin: &str,
) -> Result<DomainEntry, String> {
let subdomain = validate_subdomain(subdomain)?;
let backend = validate_backend(backend)?;
let owner = match owner {
Some(o) if !o.is_empty() => o.clone(),
_ => admin.to_owned(),
};
if crate::users::get(&owner).is_none() {
return Err(format!("归属账号不存在:{owner}"));
}
let dtype = validate_type(dtype);
let now = util::now();
let chosen = subdomain.clone();
let entry = store::update_domains(move |list| {
if let Some(idx) = list.iter().position(|e| e.subdomain == chosen) {
let existing = &list[idx];
let its_expired =
existing.dtype == "temp" && existing.effective_status(now) == "expired";
if !its_expired {
return Err(format!("子域名 {chosen} 已被占用"));
}
list.remove(idx);
}
let entry = DomainEntry {
id: util::gen_id(),
subdomain: chosen,
backend,
dtype: dtype.clone(),
owner,
status: "approved".to_owned(),
created_at: now,
expires_at: if dtype == "temp" { now + TEMP_DOMAIN_TTL } else { 0 },
reviewed_by: admin.to_owned(),
reviewed_at: now,
};
list.push(entry.clone());
Ok(entry)
})?;
sync_shm(&entry);
Ok(entry)
}
/// 用户删除自己的域名。成功返回被删的子域名(供转发侧失效)。
pub fn remove_own(id: &str, username: &str) -> Result<String, String> {
let id = id.to_owned();
let username = username.to_owned();
store::update_domains(move |list| {
let idx = list.iter().position(|e| e.id == id).ok_or("记录不存在")?;
if list[idx].owner != username {
return Err("只能删除自己的域名".to_owned());
}
let sub = list.remove(idx).subdomain;
Ok(sub)
})
.map(|sub| {
state::invalidate(sub.as_bytes());
sub
})
}
/// 管理员删除任意域名
pub fn remove(id: &str) -> Result<String, String> {
let id = id.to_owned();
store::update_domains(move |list| {
let idx = list.iter().position(|e| e.id == id).ok_or("记录不存在")?;
Ok(list.remove(idx).subdomain)
})
.map(|sub| {
state::invalidate(sub.as_bytes());
sub
})
}
/// 连带回收某账号名下的全部域名(删除账号时用)。返回回收条数。
pub fn remove_by_owner(owner: &str) -> usize {
let mut removed = 0usize;
let result = store::update_domains(|list| {
list.retain(|e| {
if e.owner == owner {
removed += 1;
false
} else {
true
}
});
Ok(())
});
if result.is_ok() && removed > 0 {
// 被回收的可能包含正在转发的域名,必须全量重载
reload_shm();
}
removed
}
/// 清理:已过期的临时域名 + 超过保留期的驳回记录。返回清理条数。
pub fn purge() -> Result<usize, String> {
let now = util::now();
let mut removed = 0usize;
store::update_domains(|list| {
list.retain(|e| {
let status = e.effective_status(now);
let stale_rejected =
status == "rejected" && (now - e.reviewed_at) > REJECTED_PURGE_TTL;
if status == "expired" || stale_rejected {
removed += 1;
false
} else {
true
}
});
Ok(())
})?;
if removed > 0 {
reload_shm();
}
Ok(removed)
}
// ===========================================================================
// 对外投影
// ===========================================================================
pub fn view(entry: &DomainEntry) -> Value {
let now = util::now();
let status = entry.effective_status(now);
let exp = entry.expires_at;
let live_temp = status == "approved" && entry.dtype == "temp" && exp > now;
json!({
"id": entry.id,
"subdomain": entry.subdomain,
"backend": entry.backend,
"type": entry.dtype,
"owner": entry.owner,
"status": status,
"created_at": entry.created_at,
"created_at_text": util::fmt_time(entry.created_at),
"expires_at": exp,
"expires_at_text": if entry.dtype == "temp" && exp > 0 { util::fmt_time(exp) } else { "-".to_owned() },
"expires_left": if live_temp { exp - now } else { 0 },
"expires_left_text": if live_temp { util::fmt_left(exp - now) } else { String::new() },
"reviewed_by": entry.reviewed_by,
"reviewed_at": entry.reviewed_at,
"auto_approved": entry.reviewed_by == "auto",
})
}
pub fn view_all(list: &[DomainEntry]) -> Vec<Value> {
list.iter().map(view).collect()
}