using System;
using System.IO;
namespace ClassNotify.Server.Services;
///
/// 当升级包存储路径非法、包含路径穿越或违反纯相对路径约束时抛出
///
public sealed class InvalidUpdatePackagePathException : Exception
{
public InvalidUpdatePackagePathException(string message = "Invalid update package path detected.") : base(message)
{
}
}
///
/// 客户端在线升级包路径解析器 (严格约束相对路径与根目录约束,防御目录穿越与跨平台大小写边界漏洞)
///
public static class UpdatePackagePathResolver
{
///
/// 将数据库中记录的纯相对 PackageRelativePath 安全解析为绝对路径
/// 严格禁止绝对路径,严格禁止任何向上逃逸 ('..')
///
public static string ResolvePackagePath(string rootDir, string? relativeStoragePath)
{
if (string.IsNullOrWhiteSpace(relativeStoragePath))
{
throw new InvalidUpdatePackagePathException("Package path cannot be empty or whitespace.");
}
// 1. 绝对路径坚决拒绝 (无论 Windows 盘符 C:\、UNC \\ 还是 Linux 根路径 / )
if (Path.IsPathRooted(relativeStoragePath))
{
throw new InvalidUpdatePackagePathException("Package path must be a relative path. Absolute paths are strictly forbidden.");
}
var root = Path.GetFullPath(rootDir).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
var candidate = Path.GetFullPath(Path.Combine(root, relativeStoragePath));
// 2. 检查相对于 root 的路径
var relative = Path.GetRelativePath(root, candidate);
if (relative == ".." ||
relative.StartsWith(".." + Path.DirectorySeparatorChar, StringComparison.Ordinal) ||
relative.StartsWith(".." + Path.AltDirectorySeparatorChar, StringComparison.Ordinal) ||
Path.IsPathRooted(relative) ||
relative == "." ||
string.IsNullOrWhiteSpace(relative) ||
string.Equals(candidate, root, StringComparison.OrdinalIgnoreCase))
{
throw new InvalidUpdatePackagePathException("Package path traversal detected.");
}
return candidate;
}
}