Files
ipass/rust/crates/plugin-domain/src/domains.rs
T
admin 74aeefee58 refactor(plugin): P0-P2 插件化落地 —— workspace 化 + ipass-core + plugin-domain
- P0: rust/ 改 workspace(ipass-core 内核 + gateway 唯一 cdylib),
  [profile.release] 上移根、依赖收敛 workspace.dependencies;
  users::delete 的 stats::forget 依赖改为 on_delete 钩子注册表
- P1: 契约层 core/plugin.rs(Plugin trait)+ core/loc.rs(Switch 并集 +
  set_switch_fn,未实现变体保守 false);gateway PLUGINS 分发循环,
  不认领统一 404(插件绝不自行 404)
- P2: 身份端点下沉 core/api.rs(CorePlugin + CoreExt 扩展注册表,
  gateway 作装配根回填域名数/用量/连带回收/白名单校验);
  plugin-domain crate(domains + DomainEntry + sub: 前缀 + ResolveHandler
  + $proxy_backend_addr + 域名类端点含 purge)
- 行为等价:conf/nginx.conf、Dockerfile、tests 零改动,262 回归全绿
- 方案文档 docs/plugin/PLUGINIZATION_PLAN.md
2026-09-13 11:43:22 +08:00

489 lines
17 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.
//! 域名(子域名映射)与申请审核。
//!
//! 数据结构见 `models::DomainEntry`。
//!
//! ## 状态机
//!
//! ```text
//! temp + 有临时授权权限 → 直接 approved(reviewed_by=auto,到时自动 expired)
//! temp + 无临时授权权限 → pending,等管理员审核
//! long + 任意 → pending,等管理员审核
//! ```
//!
//! 到期不等于删除:临时域名过期后仅「不再转发」,记录保留供查阅。
//!
//! ## 写穿
//!
//! 热路径**永不回源**(未命中即 404),所以每个写操作都必须
//! **同时更新共享内存与文件**——这就是 `sync_shm` 的存在理由。
//! 漏掉一处,就会出现「审核通过了但立刻 404」。
use serde_json::{Value, json};
use ipass_core::{state, users, util};
use crate::config::{
ENTERPRISE_ZONE, KEY_SUB_PREFIX, REJECTED_PURGE_TTL, RESERVED_SUBDOMAINS, SUBDOMAIN_GEN_ATTEMPTS,
SUBDOMAIN_MAX_LEN, SUBDOMAIN_PREFIX, SUBDOMAIN_RAND_DIGITS, SUBDOMAIN_SUFFIX, TEMP_DOMAIN_TTL,
};
use crate::models::DomainEntry;
// ===========================================================================
// 校验
// ===========================================================================
/// 子域名:小写字母/数字开头,其后可含短横线,总长 ≤ 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())
}
// ===========================================================================
// 子域名命名规则(唯一真源,前端/API 共用)
// ===========================================================================
/// 生成一个符合企业域名规则的子域名:`i` + 8 位随机数字 + `dm`(如 `i48291376dm`)。
///
/// **后缀 `dm` 不是装饰**:企业域名 server 的正则是
/// `^(.+dm)\.mayishangshu\.cn$`,捕获组必须以 `dm` 结尾,否则该域名根本不会
/// 被转发 server 匹配到。所以「i+8位+dm」是硬约束,别改后缀。
pub fn gen_subdomain() -> String {
format!(
"{SUBDOMAIN_PREFIX}{}{SUBDOMAIN_SUFFIX}",
util::rand_digits(SUBDOMAIN_RAND_DIGITS)
)
}
/// 子域名 → 完整对外域名(**不含端口**)。
///
/// 端口刻意不在这里拼:网关用宿主 88 承载三个域名,但端口应当**跟随调用方**
/// (见 readme §15),由前端按 `location.port` 拼,写死任何一种都会在另一种
/// 部署下给出「看着对、打不通」的地址。
pub fn full_host(subdomain: &str) -> String {
format!("{subdomain}.{ENTERPRISE_ZONE}")
}
pub fn validate_type(raw: Option<&String>) -> String {
match raw.map(|s| s.as_str()) {
Some("long") => "long".to_owned(),
_ => "temp".to_owned(),
}
}
// ===========================================================================
// 共享内存同步(写穿 / 装载)
// ===========================================================================
/// 把一条记录同步进共享内存。**所有写操作之后必须调用它**。
///
/// 写失败 = 热路径查不到 = 该域名立刻 404,所以失败必须出声
/// (`state::put` 返回 false:共享内存 zone 满或分配失败)。
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 };
if !state::put(
KEY_SUB_PREFIX,
entry.subdomain.as_bytes(),
entry.backend.as_bytes(),
exp,
) {
util::log_err(&format!(
"[domains] 转发映射写共享内存失败 sub={} —— 该域名会 404(共享内存可能已满)",
entry.subdomain
));
}
} else {
state::remove(KEY_SUB_PREFIX, entry.subdomain.as_bytes());
}
}
/// 全量重载转发映射(启动装载 / purge / 连带回收后调用)。返回装载条数。
///
/// 只清 `sub:` 前缀的键,**不会误伤正在登录的管理员会话**。
pub fn reload_shm() -> usize {
state::clear_prefix(KEY_SUB_PREFIX);
let now = util::now();
let mut expected = 0;
let mut loaded = 0;
for entry in crate::store::read_domains() {
if entry.is_forwardable(now) {
expected += 1;
let exp = if entry.dtype == "temp" { entry.expires_at } else { 0 };
if state::put(KEY_SUB_PREFIX, entry.subdomain.as_bytes(), entry.backend.as_bytes(), exp) {
loaded += 1;
}
}
}
if loaded != expected {
util::log_err(&format!(
"[domains] 转发映射装载不全:{loaded}/{expected} —— 有域名会 404"
));
}
loaded
}
// ===========================================================================
// 查询
// ===========================================================================
/// 全部记录,按创建时间倒序
pub fn all() -> Vec<DomainEntry> {
let mut list = crate::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> =
crate::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> {
crate::store::read_domains().into_iter().find(|e| e.id == id)
}
pub fn count_pending() -> usize {
crate::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 = 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 = crate::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 = crate::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)
}
/// 管理员直接创建并放行(等价于「我替你建好并批准」)。
///
/// `subdomain` **留空即自动生成** `i<8位随机数字>dm`(见 `gen_subdomain`),
/// 撞上已占用就换一个重试(最多 `SUBDOMAIN_GEN_ATTEMPTS` 次)。管理台与
/// `/api/admin/domains/create` 走同一条路径,规则不会两处漂移。
pub fn create_by_admin(
subdomain: &str,
backend: &str,
dtype: Option<&String>,
owner: Option<&String>,
admin: &str,
) -> Result<DomainEntry, String> {
let backend = validate_backend(backend)?;
let owner = match owner {
Some(o) if !o.is_empty() => o.clone(),
_ => admin.to_owned(),
};
if users::get(&owner).is_none() {
return Err(format!("归属账号不存在:{owner}"));
}
let dtype = validate_type(dtype);
let manual = !util::trim(subdomain).is_empty();
let attempts = if manual { 1 } else { SUBDOMAIN_GEN_ATTEMPTS };
let mut last_err = "子域名生成失败".to_owned();
for _ in 0..attempts {
let sub = if manual { validate_subdomain(subdomain)? } else { gen_subdomain() };
// 自动生成的也过一遍校验:常量被误改时立刻报错,而不是建出个用不了的域名
let sub = validate_subdomain(&sub)?;
match insert_approved(&sub, &backend, &dtype, &owner, admin) {
Ok(entry) => {
sync_shm(&entry);
return Ok(entry);
}
Err(e) => {
// 手填的子域名撞车是用户要解决的问题;自动生成的直接换一个重试
if manual {
return Err(e);
}
last_err = e;
}
}
}
Err(last_err)
}
/// 落盘一条 approved 记录(占用检查在这里);调用方负责 `sync_shm`。
fn insert_approved(
subdomain: &str,
backend: &str,
dtype: &str,
owner: &str,
admin: &str,
) -> Result<DomainEntry, String> {
let now = util::now();
let chosen = subdomain.to_owned();
let backend = backend.to_owned();
let dtype = dtype.to_owned();
let owner = owner.to_owned();
let admin = admin.to_owned();
crate::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,
reviewed_at: now,
};
list.push(entry.clone());
Ok(entry)
})
}
/// 用户删除自己的域名。成功返回被删的子域名(供转发侧失效)。
pub fn remove_own(id: &str, username: &str) -> Result<String, String> {
let id = id.to_owned();
let username = username.to_owned();
crate::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::remove(KEY_SUB_PREFIX, sub.as_bytes());
sub
})
}
/// 管理员删除任意域名
pub fn remove(id: &str) -> Result<String, String> {
let id = id.to_owned();
crate::store::update_domains(move |list| {
let idx = list.iter().position(|e| e.id == id).ok_or("记录不存在")?;
Ok(list.remove(idx).subdomain)
})
.map(|sub| {
state::remove(KEY_SUB_PREFIX, sub.as_bytes());
sub
})
}
/// 连带回收某账号名下的全部域名(删除账号时用)。返回回收条数。
pub fn remove_by_owner(owner: &str) -> usize {
let mut removed = 0usize;
let result = crate::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;
crate::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,
"host": full_host(&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()
}