namespace Chronos.Server.Storage; /// /// Archive-relative paths from the database → absolute paths, refusing anything that would leave the archive root /// (BRIEF §14.2: path traversal impossible). Clients never send paths; only ids that the database maps to these. /// public static class ArchivePathGuard { private static readonly StringComparison PathComparison = OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; /// The absolute path of under , or null when it escapes the root. public static string? Resolve(string root, string? relative) { if (string.IsNullOrWhiteSpace(relative) || relative.Contains('\0', StringComparison.Ordinal)) return null; var portable = relative.Replace('\\', '/'); if (Path.IsPathRooted(portable) || portable.StartsWith('/')) return null; string full; try { full = Path.GetFullPath(Path.Combine(Root(root), portable)); } catch (Exception ex) when (ex is ArgumentException or NotSupportedException or PathTooLongException) { return null; } return IsInside(root, full) ? full : null; } /// True when lies strictly inside . public static bool IsInside(string root, string path) { var full = Path.GetFullPath(path); return full.StartsWith(Root(root) + Path.DirectorySeparatorChar, PathComparison); } /// A file of the archive that may be served: inside the root, existing, and not a symbolic link. public static FileInfo? ExistingFile(string root, string? relative) { if (Resolve(root, relative) is not { } full) return null; var file = new FileInfo(full); return file.Exists && file.LinkTarget is null ? file : null; } private static string Root(string root) => Path.TrimEndingDirectorySeparator(Path.GetFullPath(root)); }