fix(config): 优化配置解析

- 完善 `FromLua` 转换与边界校验,拦截空洞 (`nil`) 及非整数键
This commit is contained in:
2026-08-19 11:34:16 +08:00
parent e3cb065b35
commit f59040c11e
7 changed files with 168 additions and 167 deletions

View File

@@ -1,9 +1,10 @@
use mlua::{FromLua, Lua, LuaString, ObjectLike, Table, Value};
use mlua::{FromLua, Lua, LuaString, Table, Value};
use std::collections::HashMap;
use std::ffi::OsString;
use std::fmt;
use std::fmt::Display;
use std::path::PathBuf;
use std::process::Command;
/// 构造一个带上下文的 FromLua 转换错误,便于定位配置问题
fn conversion_error(message: impl Into<String>) -> mlua::Error {
mlua::Error::FromLuaConversionError {
@@ -13,8 +14,8 @@ fn conversion_error(message: impl Into<String>) -> mlua::Error {
}
}
/// 将 Lua 字符串转为 Rust 字符串;非 UTF-8 字节替换为 U+FFFD 并告警
fn lua_string_to_os_string(s: LuaString) -> Result<OsString, mlua::Error> {
/// 将 Lua 字符串转为 Rust 字符串;非 UTF-8 按系统默认的 ANSI/OEM (如 GBK) 进行安全解码
fn lua_string_2_os_string(s: LuaString) -> mlua::Result<OsString> {
let raw_bytes = &s.as_bytes().to_vec();
// 1. Unix 平台:直接零拷贝透传原始字节(无损支持任意编码)
#[cfg(unix)]
@@ -42,7 +43,7 @@ fn lua_string_to_os_string(s: LuaString) -> Result<OsString, mlua::Error> {
}
/// 按连续整数下标遍历表的序列部分;存在空洞或非序列键时返回错误,避免静默截断
fn for_each_sequence_item(
fn validate_each_sequence_item(
tbl: &Table,
mut f: impl FnMut(Value) -> mlua::Result<()>,
) -> mlua::Result<()> {
@@ -70,9 +71,63 @@ fn for_each_sequence_item(
}
Ok(())
}
/// 值分流与上下文分发枚举
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ValueShunt {
/// 命令行参数元素:仅支持一维基础标量,禁止嵌套 Table
Args,
/// 环境变量值:支持基础标量及多维嵌套 Table递归展平
Env,
}
impl Display for ValueShunt {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Args => write!(f, "命令行参数 (args)"),
Self::Env => write!(f, "环境变量 (env)"),
}
}
}
impl ValueShunt {
fn expected_types_desc(&self) -> &str {
match self {
Self::Args => "string/number/boolean不支持嵌套数组",
Self::Env => "string/number/boolean 或包含这些类型的数组/嵌套数组",
}
}
/// 递归/标量收集实现
pub fn collect_into(&self, value: Value, out: &mut Vec<OsString>) -> mlua::Result<()> {
match value {
Value::Nil => {}
Value::String(s) => out.push(lua_string_2_os_string(s)?),
Value::Integer(i) => out.push(OsString::from(i.to_string())),
Value::Number(n) => {
tracing::warn!(context = %self, value = %n, "浮点数将按十进制格式转换为字符串");
out.push(OsString::from(n.to_string()));
}
Value::Boolean(b) => {
tracing::warn!(context = %self, value = %b, "布尔值将转换为字符串");
out.push(OsString::from(b.to_string()));
}
// 嵌套 Table 仅在 EnvValue 下允许递归展开(支持 get_env("PATH") 等返回的子表)
Value::Table(tbl) if *self == Self::Env => {
validate_each_sequence_item(&tbl, |item| self.collect_into(item, out))?;
}
other => {
return Err(conversion_error(format!(
"{} 不支持类型 {}(仅支持 {}",
self,
other.type_name(),
self.expected_types_desc()
)));
}
}
Ok(())
}
}
/// 校验环境变量名的合法性Windows 约束:非空、不含 '='、不含 NUL
fn validate_env_key(key: &str) -> mlua::Result<()> {
fn validate_env_var_name(key: &str) -> mlua::Result<()> {
if key.is_empty() {
return Err(conversion_error("环境变量名不能为空"));
}
@@ -92,10 +147,10 @@ fn validate_env_key(key: &str) -> mlua::Result<()> {
}
/// 递归将任意 Lua Value 展开为扁平的字符串片段列表
fn collect_env_strings(value: Value, out: &mut Vec<OsString>) -> mlua::Result<()> {
fn collect_env_segments(value: Value, out: &mut Vec<OsString>) -> mlua::Result<()> {
match value {
// 1. 字符串
Value::String(s) => out.push(lua_string_to_os_string(s)?),
Value::String(s) => out.push(lua_string_2_os_string(s)?),
// 2. 整数与浮点数
Value::Integer(i) => out.push(OsString::from(i.to_string())),
Value::Number(n) => {
@@ -108,7 +163,9 @@ fn collect_env_strings(value: Value, out: &mut Vec<OsString>) -> mlua::Result<()
out.push(OsString::from(b.to_string()));
}
// 4. 表/数组:必须是连续整数下标的纯序列,递归解包(支持任意深度的嵌套数组)
Value::Table(tbl) => for_each_sequence_item(&tbl, |item| collect_env_strings(item, out))?,
Value::Table(tbl) => {
validate_each_sequence_item(&tbl, |item| collect_env_segments(item, out))?
}
// 5. 安全忽
// 略 nil
Value::Nil => {}
@@ -170,7 +227,7 @@ impl FromLua for ShimConfig {
// 必填字段: target严格限定为字符串避免数字被 mlua 宽松转为字符串后掩盖错误)
let target = match table.get::<Value>("target")? {
Value::String(s) => lua_string_to_os_string(s)?,
Value::String(s) => lua_string_2_os_string(s)?,
Value::Nil => {
return Err(conversion_error("缺少必填字段 target应为字符串路径"));
}
@@ -181,90 +238,76 @@ impl FromLua for ShimConfig {
)));
}
};
let mut args = Vec::new();
// 可选字段: args缺失或 nil 时默认空列表;保留空字符串参数,与提权路径的 "" 语义一致)
// let args = match table.get::<Option<Value>>("args")? {
// None => Vec::new(),
// Some(Value::Table(tbl)) => {
// let mut args = Vec::new();
// for_each_sequence_item(&tbl, |item| match item {
// Value::String(s) => {
// args.push(lua_string_to_string(s));
// Ok(())
// }
// other => Err(conversion_error(format!(
// "args 数组元素必须是字符串,实际是 {}",
// other.type_name()
// ))),
// })?;
// args
// }
let args = match table.get::<Option<Value>>("args")? {
None => Vec::new(),
match table.get::<Option<Value>>("args")? {
None | Some(Value::Nil) => {}
Some(Value::Table(tbl)) => {
let mut args = Vec::new();
for_each_sequence_item(&tbl, |item| match item {
Value::String(s) => {
args.push(lua_string_to_os_string(s)?);
Ok(())
}
other => Err(conversion_error(format!(
"args 数组元素必须是字符串,实际是 {}",
other.type_name()
))),
validate_each_sequence_item(&tbl, |item| {
ValueShunt::Args.collect_into(item, &mut args)
})?;
args
}
Some(other) => {
return Err(conversion_error(format!(
"args 必须是字符串数组,实际是 {}",
"args 必须是数组列表,实际类型{}",
other.type_name()
)));
}
};
// 可选字段: env只允许缺失/nil其他类型由 Option<Table> 转换报错,不再静默忽略)
let env_table = table.get::<Option<Table>>("env")?;
let env_table = table.get::<Option<Value>>("env")?;
println!("env_table:{:?}", env_table);
let mut env = HashMap::new();
if let Some(env_table) = env_table {
for pair in env_table.pairs::<String, Value>() {
let (key, value) = pair?;
validate_env_key(&key)?;
match env_table {
None | Some(Value::Nil) => {}
Some(Value::Table(tbl)) => {
for pair in tbl.pairs::<String, Value>() {
let (name, value) = pair?;
validate_env_var_name(&name)?;
let mut parts = Vec::new();
collect_env_strings(value, &mut parts)?;
let mut parts = Vec::new();
ValueShunt::Env.collect_into(value, &mut parts)?;
// 空数组/空串也显式设置(空值表示清空该变量),
// 与“未配置该变量(继承宿主环境)”相区分
let joined_os_str = std::env::join_paths(parts).map_err(|e| {
conversion_error(format!(
"环境变量 [{}] 的值无法用系统路径分隔符拼接: {}",
key, e
))
})?;
println!("环境变量拼接结果:{:?}", joined_os_str);
// 检查是否包含非法 NUL 字符
#[cfg(unix)]
{
use std::os::unix::ffi::OsStrExt;
if joined_os_str.as_bytes().contains(&0) {
return Err(conversion_error(format!(
"环境变量 [{}] 的值不能包含 NUL 字符",
key
)));
// 空数组/空串也显式设置(空值表示清空该变量),
// 与“未配置该变量(继承宿主环境)”相区分
let joined_os_str = std::env::join_paths(parts).map_err(|e| {
conversion_error(format!(
"环境变量 [{}] 的值无法用系统路径分隔符拼接: {}",
name, e
))
})?;
println!("环境变量拼接结果:{:?}", joined_os_str);
// 检查是否包含非法 NUL 字符
#[cfg(unix)]
{
use std::os::unix::ffi::OsStrExt;
if joined_os_str.as_bytes().contains(&0) {
return Err(conversion_error(format!(
"环境变量 [{}] 的值不能包含 NUL 字符",
key
)));
}
}
}
#[cfg(windows)]
{
use std::os::windows::ffi::OsStrExt;
if joined_os_str.encode_wide().any(|c| c == 0) {
return Err(conversion_error(format!(
"环境变量 [{}] 的值不能包含 NUL 字符",
key
)));
#[cfg(windows)]
{
use std::os::windows::ffi::OsStrExt;
if joined_os_str.encode_wide().any(|c| c == 0) {
return Err(conversion_error(format!(
"环境变量 [{}] 的值不能包含 NUL 字符",
name
)));
}
}
}
env.insert(key, joined_os_str);
env.insert(name, joined_os_str);
}
}
Some(other) => {
return Err(conversion_error(format!(
"env 必须是键值表 (table),实际类型是 {}",
other.type_name()
)));
}
}
println!("环境变量结果:{:?}", env);
@@ -315,7 +358,11 @@ mod tests {
PATH = { "C:/tools/git/bin", "C:/Windows",get_env("PATH") },
HOME = "C:/tools/home",
CONST = 3,
BOOL = true
BOOL = true
MUT ={
A=3
B=true
}
}
}
"#,