using System;
using System.IO;
using System.Threading.Tasks;
using NewLife;
using Stardust.Data.Deployment;
using Stardust.Models;
using Stardust.Server;
using Stardust.Server.Services;
using Xunit;
namespace ServerTest.Relay;
/// <summary>资源中转服务静态规则与缓存落盘测试</summary>
public class RelayServiceTests
{
[Theory(DisplayName = "只允许 http/https 且拒绝本机回环")]
[InlineData("https://x.newlifex.com/dotnet/net8.sh", true)]
[InlineData("http://builds.dotnet.microsoft.com/a.zip", true)]
[InlineData("ftp://example.com/a.zip", false)]
[InlineData("file:///etc/passwd", false)]
[InlineData("http://localhost/a.zip", false)]
[InlineData("http://127.0.0.1/a.zip", false)]
[InlineData("not a url", false)]
public void IsUrlAllowed_Basic(String url, Boolean expected)
{
Assert.Equal(expected, RelayService.IsUrlAllowed(url));
}
[Fact(DisplayName = "超长地址一律拒绝")]
public void IsUrlAllowed_Length()
{
Assert.False(RelayService.IsUrlAllowed("https://x.newlifex.com/" + new String('a', 500)));
}
[Theory(DisplayName = "缓存相对路径拒绝越界与绝对路径")]
[InlineData("dotnet/net8.sh", "dotnet/net8.sh")]
[InlineData("/dotnet/net8.sh/", "dotnet/net8.sh")]
[InlineData("dotnet\\net8.sh", "dotnet/net8.sh")]
[InlineData("../etc/passwd", null)]
[InlineData("C:\\Windows\\win.ini", null)]
[InlineData("", null)]
public void NormalizeSubpath_Cases(String input, String expected)
{
Assert.Equal(expected, RelayService.NormalizeSubpath(input));
}
[Fact(DisplayName = "文件名从地址推导并清理非法字符")]
public void SafeFileName_Cases()
{
Assert.Equal("net8.sh", RelayService.SafeFileName("https://x.newlifex.com/dotnet/net8.sh?x=1"));
Assert.Equal("a_b.zip", RelayService.SafeFileName("a_b.zip"));
Assert.Equal("b.zip", RelayService.SafeFileName("a:b.zip"));
Assert.Equal("download.bin", RelayService.SafeFileName(null));
}
[Fact(DisplayName = "任务状态可在附件 Remark 中往返")]
public void State_RoundTrip()
{
var att = new Attachment { Category = "Relay" };
RelayService.SetState(att, new RelayTaskState
{
Node = "ABC",
Path = "dotnet/net8.sh",
Retry = 1,
Msg = "boom",
Hash = "sha512:abc",
Size = 1024,
});
var state = RelayService.GetState(att);
Assert.NotNull(state);
Assert.Equal("ABC", state!.Node);
Assert.Equal("dotnet/net8.sh", state.Path);
Assert.Equal(1, state.Retry);
Assert.Equal("boom", state.Msg);
Assert.Equal("sha512:abc", state.Hash);
Assert.Equal(1024, state.Size);
}
[Fact(DisplayName = "缓存文件写入 FileCache 且按子路径创建目录")]
public void CopyToCache_WritesFile()
{
var root = Path.Combine(Path.GetTempPath(), "star-relay-test-" + Guid.NewGuid().ToString("N"));
var upload = Path.Combine(root, "Uploads");
var cache = Path.Combine(root, "FileCache");
Directory.CreateDirectory(upload);
Directory.CreateDirectory(cache);
try
{
var setting = new StarServerSetting { UploadPath = upload, FileCache = cache };
var service = new RelayService(null!, setting);
var relative = "Relay/20260101/1.bin";
var source = Path.Combine(upload, relative.Replace('/', Path.DirectorySeparatorChar));
Directory.CreateDirectory(Path.GetDirectoryName(source)!);
File.WriteAllText(source, "hello relay");
var att = new Attachment { Id = 1, Category = "Relay", FilePath = relative, FileName = "1.bin" };
Assert.True(service.CopyToCache(att, "dotnet/net8.sh"));
var target = Path.Combine(cache, "dotnet", "net8.sh");
Assert.True(File.Exists(target));
Assert.Equal("hello relay", File.ReadAllText(target));
}
finally
{
if (Directory.Exists(root)) Directory.Delete(root, true);
}
}
[Fact(DisplayName = "任务状态超长时丢弃可选字段但保持可解析")]
public void State_TruncationKeepsValidJson()
{
var att = new Attachment { Category = "Relay" };
RelayService.SetState(att, new RelayTaskState
{
Node = "ABC",
Path = new String('p', 200),
Hash = "sha512:" + new String('a', 128),
Msg = new String('m', 400),
Retry = 1,
});
// 压缩消息、丢弃可选哈希后仍是合法 JSON,Node/Path 必须保留
var state = RelayService.GetState(att);
Assert.NotNull(state);
Assert.Equal("ABC", state!.Node);
Assert.NotNull(state.Path);
Assert.Null(state.Hash);
Assert.Equal(1, state.Retry);
Assert.True(att.Remark.Length <= 500);
}
[Fact(DisplayName = "创建任务时拒绝超过 200 字符的哈希")]
public async Task Create_TooLongHash_Rejected()
{
var old = StarServerSetting.Current.RelayNodes;
try
{
StarServerSetting.Current.RelayNodes = "TEST-NODE";
var service = new RelayService(null!, StarServerSetting.Current);
await Assert.ThrowsAsync<InvalidOperationException>(() => service.CreateAsync("https://x.newlifex.com/a.zip", hash: new String('a', 201)));
}
finally
{
StarServerSetting.Current.RelayNodes = old;
}
}
[Fact(DisplayName = "未配置中转节点时也能复用已同步的缓存文件")]
public async Task EnsureCacheFile_ReuseSyncedFileWithoutNodes()
{
var oldNodes = StarServerSetting.Current.RelayNodes;
var oldUpload = StarServerSetting.Current.UploadPath;
var oldCache = StarServerSetting.Current.FileCache;
var root = Path.Combine(Path.GetTempPath(), "relay-cache-" + Guid.NewGuid().ToString("n"));
var upload = Path.Combine(root, "Uploads");
var cache = Path.Combine(root, "FileCache");
Directory.CreateDirectory(upload);
Directory.CreateDirectory(cache);
var id = Guid.NewGuid().ToString("n");
var source = "https://x.newlifex.com/cache-" + id + ".zip";
var subpath = "dotnet/cache-" + id + ".zip";
var att = new Attachment
{
Category = "RelayCache",
Key = source.MD5(),
Title = "cache",
FileName = "cache-" + id + ".zip",
FilePath = "RelayCache/" + id + ".bin",
Source = source,
UploadTime = DateTime.Now,
Enable = true,
Storage = "Local",
};
att.Insert();
try
{
StarServerSetting.Current.RelayNodes = "";
StarServerSetting.Current.UploadPath = upload;
StarServerSetting.Current.FileCache = cache;
var file = Path.Combine(upload, att.FilePath.Replace('/', Path.DirectorySeparatorChar));
Directory.CreateDirectory(Path.GetDirectoryName(file)!);
File.WriteAllText(file, "cached");
// 本实例没有配置中转节点,但附件已由别的实例取回并同步到共享上传目录
var service = new RelayService(null!, StarServerSetting.Current);
Assert.True(await service.EnsureCacheFileAsync(subpath, source));
Assert.True(File.Exists(Path.Combine(cache, subpath.Replace('/', Path.DirectorySeparatorChar))));
}
finally
{
StarServerSetting.Current.RelayNodes = oldNodes;
StarServerSetting.Current.UploadPath = oldUpload;
StarServerSetting.Current.FileCache = oldCache;
att.Delete();
if (Directory.Exists(root)) Directory.Delete(root, true);
}
}
[Fact(DisplayName = "未配置中转节点时缓存回源直接放弃")]
public async Task EnsureCacheFile_NoNodes()
{
var old = StarServerSetting.Current.RelayNodes;
try
{
StarServerSetting.Current.RelayNodes = "";
var service = new RelayService(null!, StarServerSetting.Current);
var ok = await service.EnsureCacheFileAsync("dotnet/missing-" + Guid.NewGuid().ToString("n") + ".zip");
Assert.False(ok);
}
finally
{
StarServerSetting.Current.RelayNodes = old;
}
}
[Theory(DisplayName = "创建任务时拒绝非法或超长地址")]
[InlineData("ftp://example.com/a.zip")]
[InlineData("not a url")]
public async Task Create_InvalidUrl_Rejected(String url)
{
var service = new RelayService(null!, StarServerSetting.Current);
await Assert.ThrowsAsync<InvalidOperationException>(() => service.CreateAsync(url));
}
[Fact(DisplayName = "创建任务时拒绝超过 400 字符的地址")]
public async Task Create_TooLongUrl_Rejected()
{
var old = StarServerSetting.Current.RelayNodes;
try
{
// 必须配置节点,否则会先命中“未启用中转”分支而测不到长度校验
StarServerSetting.Current.RelayNodes = "TEST-NODE";
var service = new RelayService(null!, StarServerSetting.Current);
var url = "https://x.newlifex.com/" + new String('a', RelayService.MaxUrlLength);
var ex = await Assert.ThrowsAsync<InvalidOperationException>(() => service.CreateAsync(url));
Assert.Contains(RelayService.MaxUrlLength + "", ex.Message);
}
finally
{
StarServerSetting.Current.RelayNodes = old;
}
}
}
|