云库增加 AI识图,缓存,我的云库收藏增加安全标志

调用外部API 扣费
This commit is contained in:
chfei committed 2026-11-06 19:25:36 +08:00
1 parent 7c29e57623
commit 150e8644b7
49 files changed
+1069 -28

No files matched your search

@@ -3,6 +3,7 @@
<OutputType>Exe</OutputType>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="FreeSql.Provider.Sqlite" Version="3.5.311" />
<ProjectReference Include="../../Plugins/CloudProduct/Store.CloudProduct.csproj" />
</ItemGroup>
</Project>
+78
View File
@@ -56,6 +56,77 @@ Reject(() => GoodsViolationService.ValidateAndGroup([new() { GoodsId = 1, Reason
// SQL generation only: no database connection or production data access.
using var db = new FreeSql.FreeSqlBuilder().UseConnectionString(FreeSql.DataType.MySql,
"Server=127.0.0.1;Database=checks;User Id=unused;Password=unused").Build();
// 在内存库验证真实的收藏更新语句和用户隔离,不连接配置中的商品库。
using (var favoriteDb = new FreeSql.FreeSqlBuilder()
.UseConnectionString(FreeSql.DataType.Sqlite, "Data Source=:memory:;Max Pool Size=1").Build())
{
favoriteDb.CodeFirst.SyncStructure<UserGoodsFavoriteEntity>();
favoriteDb.Insert(new[] { "alice", "bob" }.Select(name => new UserGoodsFavoriteEntity
{ UserName = name, GoodsId = 123, CreatedAt = DateTime.Now }).ToArray()).ExecuteAffrows();
var serviceTypeForFavorites = typeof(IUserFavoritesService).Assembly.GetType("Store.Modules.CloudProduct.Services.UserFavoritesService")!;
using var searchContext = new PluginContext("CloudProduct", "Plugins/CloudProduct", new HostingEnvironment());
var indexType = typeof(IUserFavoritesIndexService).Assembly.GetType("Store.Modules.CloudProduct.Services.UserFavoritesIndexService")!;
var index = (IUserFavoritesIndexService)Activator.CreateInstance(indexType, searchContext, null)!;
var indexName = searchContext.Configuration["Search:FavoritesIndexName"]!;
IApiCallDetails? call = null;
void Respond(string body, int status = 200)
{
var settings = new ConnectionSettings(new SingleNodeConnectionPool(new Uri("http://localhost:9200")),
new InMemoryConnection(Encoding.UTF8.GetBytes(body), status)).DefaultIndex(indexName)
.DisableDirectStreaming().OnRequestCompleted(details => call = details);
indexType.GetField("_client", BindingFlags.Instance | BindingFlags.NonPublic)!.SetValue(index, new OpenSearchClient(settings));
}
Respond("""{"result":"updated","_shards":{"successful":1,"failed":0}}""");
var favorites = (IUserFavoritesService)Activator.CreateInstance(serviceTypeForFavorites,
new Store.Modules.CloudProduct.Repositorys.UserGoodsFavoriteRepository(favoriteDb), null, null, index, null, new LocalFavoritesLock(searchContext))!;
foreach (var safe in new[] { true, false, false })
{
await favorites.SaveProductSafetyAsync(new() { UserName = "alice", ProductId = "123", IsSafe = safe });
using var update = JsonDocument.Parse(call!.RequestBodyInBytes);
Check(update.RootElement.GetProperty("doc").GetProperty("is_safe").GetBoolean() == safe &&
Uri.UnescapeDataString(call.Uri.AbsolutePath).EndsWith("/_update/alice:123") && call.Uri.Query.Contains("refresh=wait_for"),
"Refresh the matching document after a partial safety update");
var rows = favoriteDb.Select<UserGoodsFavoriteEntity>().ToList().ToDictionary(x => x.UserName);
Check(rows["alice"].IsSafe == safe && rows["bob"].IsSafe == null, "Safety updates only the matching favorite");
}
Reject(() => favorites.SaveProductSafetyAsync(new() { UserName = "alice", ProductId = "999", IsSafe = true }).GetAwaiter().GetResult());
Respond("""{"error":{"type":"document_missing_exception","reason":"missing"},"status":404}""", 404);
Reject(() => favorites.SaveProductSafetyAsync(new() { UserName = "alice", ProductId = "123", IsSafe = true }).GetAwaiter().GetResult());
Check(favoriteDb.Select<UserGoodsFavoriteEntity>().Where(x => x.UserName == "alice").First().IsSafe == false, "Roll back on index failure");
Respond("""{"hits":{"total":{"value":12,"relation":"eq"},"hits":[{"_source":{"goods_id":123,"is_safe":false}}]}}""");
var page = await favorites.SearchFavoritesAsync(new() { UserName = "alice", Status = 2, PageIndex = 2, PageSize = 10 });
using var query = JsonDocument.Parse(call!.RequestBodyInBytes);
var filters = query.RootElement.GetProperty("query").GetProperty("bool").GetProperty("filter");
Check(filters.EnumerateArray().Any(f => f.GetProperty("term").TryGetProperty("is_safe", out var term) &&
!term.GetProperty("value").GetBoolean()) && query.RootElement.GetProperty("from").GetInt32() == 10,
"Apply safety filter inside paged OpenSearch query");
Check(page.Total == 12 && page.List.Single().IsSafe == false, "Read safety and filtered total from index");
Respond("""{"hits":{"total":{"value":1,"relation":"eq"},"hits":[{"_source":{"goods_id":123}}]}}""");
var jsonOptions = new JsonSerializerOptions(JsonSerializerDefaults.Web);
var omitted = JsonSerializer.Deserialize<UserFavoritesSearchRequest>("""{"userName":"alice"}""", jsonOptions)!;
await favorites.SearchFavoritesAsync(omitted);
using var allQuery = JsonDocument.Parse(call!.RequestBodyInBytes);
Check(allQuery.RootElement.GetProperty("query").GetProperty("bool").GetProperty("filter").GetArrayLength() == 1,
"Omitting status applies only the user filter");
await favorites.SearchFavoritesAsync(new() { UserName = "alice", Status = 0 });
using var zeroQuery = JsonDocument.Parse(call!.RequestBodyInBytes);
Check(zeroQuery.RootElement.GetProperty("query").GetProperty("bool").GetProperty("filter").GetArrayLength() == 1, "Status 0 includes all");
await favorites.SearchFavoritesAsync(new() { UserName = "alice", Status = 1 });
using var safeQuery = JsonDocument.Parse(call!.RequestBodyInBytes);
Check(safeQuery.RootElement.GetProperty("query").GetProperty("bool").GetProperty("filter").EnumerateArray()
.Any(f => f.GetProperty("term").TryGetProperty("is_safe", out var term) && term.GetProperty("value").GetBoolean()), "Status 1 selects safe");
foreach (int invalid in new[] { -1, 4 })
Reject(() => favorites.SearchFavoritesAsync(new() { UserName = "alice", Status = invalid }).GetAwaiter().GetResult());
var uncheckedRequest = JsonSerializer.Deserialize<UserFavoritesSearchRequest>("""{"userName":"alice","status":3}""", jsonOptions)!;
var uninspected = await favorites.SearchFavoritesAsync(uncheckedRequest);
using var missingQuery = JsonDocument.Parse(call!.RequestBodyInBytes);
var missingFilters = missingQuery.RootElement.GetProperty("query").GetProperty("bool").GetProperty("filter");
Check(missingFilters.GetArrayLength() == 2 && missingFilters.EnumerateArray().Any(f => f.TryGetProperty("bool", out var clause)
&& clause.GetProperty("must_not")[0].GetProperty("exists").GetProperty("field").GetString() == "is_safe"),
"Status 3 selects missing safety values alongside the user filter");
Check(uninspected.List.Single().IsSafe == null, "Missing safety remains null");
Check(favoriteDb.Select<UserGoodsFavoriteEntity>().Count() == 2, "Safety reports never create favorites");
}
var sql = db.Select<GoodsEntity>().As("g")
.Where(x => x.Status == 0 && x.IsSegmented == 0)
.Where("NOT EXISTS (SELECT 1 FROM goods_violation v WHERE v.goods_id = g.goods_id)")
@@ -129,3 +200,10 @@ await TestDelete(200, """{"errors":true,"items":[{"delete":{"_index":"goods","_i
await TestDelete(200, """{"errors":true,"items":[{"delete":{"_index":"goods","_id":"123","status":429,"error":{"type":"rejected","reason":"busy"}}}]}""", true);
await TestDelete(200, """{"errors":false,"items":[]}""", true);
Console.WriteLine($"PASS: {checks} checks (no external services accessed)");
// SQLite 检查独占内存库,无需获取 MySQL 会话锁。
sealed class LocalFavoritesLock(PluginContext context) : GoodsIndexLock(context), IAsyncDisposable
{
public override Task<IAsyncDisposable> AcquireFavoritesAsync() => Task.FromResult<IAsyncDisposable>(this);
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
}
@@ -0,0 +1,8 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="../../Plugins/CloudProduct/Store.CloudProduct.csproj" />
</ItemGroup>
</Project>
@@ -0,0 +1,68 @@
using System.ComponentModel.DataAnnotations;
using MAX.Plugins;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.AspNetCore.Hosting.Server.Features;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Store.Modules.CloudProduct;
using Store.Modules.CloudProduct.Services;
// 本地模拟站点验证服务自行创建的 HttpClient,不调用真实扣费接口。
var builder = WebApplication.CreateBuilder();
builder.Logging.ClearProviders();
builder.WebHost.UseUrls("http://127.0.0.1:0");
await using var app = builder.Build();
var calls = 0;
var status = 200;
app.MapPost("/wxxd_user/UseImageAnalysisQuota", async (HttpContext http) =>
{
calls++;
if (http.Request.Query["token"] != "key+&=?" || http.Request.Query["username"] != "用户 +&=?")
throw new Exception("查询参数编码不符合外部协议。");
http.Response.StatusCode = status;
await http.Response.WriteAsync("{\"success\":true}");
});
await app.StartAsync();
var address = app.Services.GetRequiredService<IServer>().Features.Get<IServerAddressesFeature>()!.Addresses.Single();
using var context = new PluginContext("CloudProduct", "Plugins/CloudProduct", builder.Environment);
context.Configuration["ImageAnalysisQuota:APIKey"] = "key+&=?";
var typedContext = new PluginContext<CloudProductPlugin>(context);
// 根地址带或不带末尾斜杠时,都应命中固定接口路径。
foreach (var url in new[] { address, address + "/" })
{
context.Configuration["ImageAnalysisQuota:Url"] = url;
using var service = new ImageAnalysisQuotaService(typedContext);
var body = await service.UseImageAnalysisQuotaAsync(new() { Username = "用户 +&=?" });
if (body != "{\"success\":true}") throw new Exception("应返回原始响应。");
await RejectAsync<ValidationException>(() => service.UseImageAnalysisQuotaAsync(new() { Username = " " }));
context.Configuration["ImageAnalysisQuota:APIKey"] = "";
await RejectAsync<InvalidOperationException>(() => service.UseImageAnalysisQuotaAsync(new() { Username = "test" }));
context.Configuration["ImageAnalysisQuota:APIKey"] = "key+&=?";
}
if (calls != 2) throw new Exception("无效输入或配置不能发送扣减请求。");
context.Configuration["ImageAnalysisQuota:Url"] = "file:///invalid";
await RejectAsync<InvalidOperationException>(() =>
{
using var invalid = new ImageAnalysisQuotaService(typedContext);
return Task.CompletedTask;
});
context.Configuration["ImageAnalysisQuota:Url"] = address;
using (var service = new ImageAnalysisQuotaService(typedContext))
{
status = 500;
await RejectAsync<HttpRequestException>(() => service.UseImageAnalysisQuotaAsync(new() { Username = "用户 +&=?" }));
}
if (calls != 3) throw new Exception("失败请求不能自动重试。");
await app.StopAsync();
Console.WriteLine("Image analysis quota checks passed.");
static async Task RejectAsync<T>(Func<Task> action) where T : Exception
{
try { await action(); }
catch (T) { return; }
throw new Exception($"应抛出 {typeof(T).Name}。");
}
+26 -1
View File
@@ -25,7 +25,7 @@ catch (TargetInvocationException ex) when (mode == "failure" && ex.InnerExceptio
return;
}
if (mode == "failure") throw new Exception("Expected loading failure");
var plugins = assemblies.Where(a => a.GetName().Name is "Store.CloudProduct" or "Store.ImageCache").ToArray();
var plugins = assemblies.Where(a => a.GetName().Name is "Store.CloudProduct" or "Store.ImageCache" or "Store.ProductInspection").ToArray();
if (mode == "empty")
{
if (plugins.Length != 0) throw new Exception("Unexpected plugins");
@@ -43,6 +43,8 @@ if (mode != "image" && !feature.Controllers.Any(t => t.Name == "GoodsController"
if (mode is "image" or "plugins")
{
var host = Host.CreateApplicationBuilder();
host.Services.AddHttpContextAccessor();
host.Services.AddScoped<MAX.Framework.Security.ICurrentUser, MAX.Framework.Security.CurrentUser>();
var core = typeof(ServiceCollectionExtensions).GetMethod("AddStoreCore", BindingFlags.Static | BindingFlags.NonPublic)!;
host.Configuration["Search:Url"] = "https://host.invalid";
host.Configuration["ImageCache:ConnectionString"] = "host-only";
@@ -50,12 +52,35 @@ if (mode is "image" or "plugins")
if (host.Services.Any(d => d.ServiceType == typeof(Hangfire.JobStorage)))
throw new Exception("Plugins must not register shared Hangfire storage");
using var built = host.Build();
foreach (var pluginType in plugins.SelectMany(a => a.GetTypes()).Where(t => !t.IsAbstract && typeof(IPlugin).IsAssignableFrom(t)))
{
var contextType = typeof(PluginContext<>).MakeGenericType(pluginType);
// 先解析泛型入口,确认无需提前解析键名上下文。
var typed = built.Services.GetRequiredService(contextType);
var id = (string)contextType.GetProperty("Id")!.GetValue(typed)!;
var keyed = built.Services.GetRequiredKeyedService<PluginContext>(id);
if (!ReferenceEquals(contextType.GetProperty("Configuration")!.GetValue(typed), keyed.Configuration)
|| !Equals(contextType.GetProperty("DirectoryPath")!.GetValue(typed), keyed.DirectoryPath)
|| !ReferenceEquals(contextType.GetProperty("Environment")!.GetValue(typed), keyed.Environment))
throw new Exception("Typed context must share the plugin configuration and environment");
using var scope = built.Services.CreateScope();
if (!ReferenceEquals(typed, scope.ServiceProvider.GetRequiredService(contextType)))
throw new Exception("Typed plugin context must be singleton");
}
var image = built.Services.GetRequiredKeyedService<PluginContext>("ImageCache");
if (image.Configuration["ImageCache:ConnectionString"] is null or "host-only") throw new Exception("Image config isolation failed");
if (image.Configuration["Search:Url"] != null) throw new Exception("Host settings leaked into ImageCache");
if (host.Configuration["ImageCache:ConnectionString"] != "host-only") throw new Exception("Plugin modified host configuration");
if (mode == "plugins")
{
var inspection = plugins.Single(p => p.GetName().Name == "Store.CloudProduct");
using (var scope = built.Services.CreateScope())
{
scope.ServiceProvider.GetRequiredService(inspection.GetTypes().Single(t => t.Name == "ProductInspectionService"));
scope.ServiceProvider.GetRequiredService(inspection.GetTypes().Single(t => t.Name == "QwenInspectionIntegration"));
}
if (!feature.Controllers.Any(t => t.Name == "ProductInspectionController"))
throw new Exception("Product inspection controller missing");
var cloud = built.Services.GetRequiredKeyedService<PluginContext>("CloudProduct");
if (cloud.Configuration["Search:Url"] is null or "https://host.invalid") throw new Exception("Cloud config isolation failed");
if (host.Configuration["Search:Url"] != "https://host.invalid") throw new Exception("Cloud modified host configuration");
@@ -0,0 +1,141 @@
using System.Net;
using System.Net.Http.Json;
using System.Security.Claims;
using System.Text.Encodings.Web;
using System.Text.Json;
using MAX.Framework.Commons;
using MAX.Framework.Security;
using MAX.Plugins;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.AspNetCore.Hosting.Server.Features;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Store.Modules.CloudProduct.Controllers;
using Store.Modules.CloudProduct.Entities;
using Store.Modules.CloudProduct.Services;
/// <summary>通过真实 HTTP 路由验证图片识别的 DTO 绑定、ApiResult 包装及缓存。</summary>
internal static class HttpChecks
{
public static async Task RunAsync(IFreeSql database)
{
var userName = "http-check-" + Guid.NewGuid().ToString("N");
var builder = WebApplication.CreateBuilder();
builder.Logging.ClearProviders();
builder.WebHost.UseUrls("http://127.0.0.1:0");
using var context = new PluginContext("CloudProduct", "Plugins/CloudProduct", builder.Environment);
context.Configuration["ProductInspection:Model"] = "test-vision";
context.Configuration["ProductInspection:ApiKey"] = "test-key";
builder.Services.AddSingleton(new PluginContext<Store.Modules.CloudProduct.CloudProductPlugin>(context));
builder.Services.AddKeyedSingleton<SemaphoreSlim>("ProductInspectionAnalysisGate", (_, _) => new SemaphoreSlim(5, 5));
builder.Services.AddKeyedSingleton<IFreeSql>("ProductInspectionConnection", database);
builder.Services.AddSingleton<Store.Modules.CloudProduct.Contracts.IInspectionIntegration, QwenInspectionIntegration>();
builder.Services.AddScoped<ProductInspectionService>();
builder.Services.AddHttpContextAccessor();
builder.Services.AddScoped<ICurrentUser, CurrentUser>();
builder.Services.AddAuthentication("test").AddScheme<AuthenticationSchemeOptions, TestAuthentication>("test", _ => { });
builder.Services.AddAuthorization();
builder.Services.AddControllers(options =>
{
options.Conventions.Add(new MAX.Framework.Conventions.ApiRoutePrefixConvention());
options.Filters.Add<UnifyResultFilter>();
options.Filters.Add<GlobalExceptionFilter>();
}).AddApplicationPart(typeof(ProductInspectionController).Assembly);
await using var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.MapPost("/test/chat", RecognitionEndpoint.RespondAsync);
await app.StartAsync();
var address = app.Services.GetRequiredService<IServer>().Features.Get<IServerAddressesFeature>()!.Addresses.Single();
context.Configuration["ProductInspection:Endpoint"] = address + "/test/chat";
using var client = new HttpClient { BaseAddress = new Uri(address + "/api/ProductInspection/") };
var checks = 0;
void Check(bool condition, string message)
{
if (!condition) throw new Exception(message);
checks++;
}
// 随机化图片内容及登录身份,清理时只删除本次检查创建的行。
var data = Convert.FromBase64String("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jZQAAAABJRU5ErkJggg==")
.Concat(Guid.NewGuid().ToByteArray()).ToArray();
var image = Convert.ToBase64String(data);
var key = Guid.NewGuid().ToString("N");
async Task<JsonElement> Inspect(string image, string? md5)
{
using var response = await client.PostAsJsonAsync("InspectImage", new { userName, md5, image });
using var doc = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
return doc.RootElement.Clone();
}
try
{
client.DefaultRequestHeaders.Add("X-Test-User", userName);
var first = await Inspect(image, key.ToUpperInvariant());
Check(first.TryGetProperty("code", out var firstCode) && firstCode.GetInt32() == 200, first.ToString());
string[] expected = ["急速发货", "螺旋伸缩", "金属挂钩", "可调节", "不挡扇叶", "倒挂钩卡口"];
Check(first.GetProperty("data").Deserialize<string[]>()!.SequenceEqual(expected), "Ordered recognition array");
Check((await Inspect(image, key)).GetProperty("data").Deserialize<string[]>()!.SequenceEqual(expected), "Cache hit preserves item order");
var stored = await database.Select<ImageAnalysisCache>().Where(x => x.CacheKey == key).FirstAsync();
Check(stored.RecognitionResult == """["急速发货","螺旋伸缩","金属挂钩","可调节","不挡扇叶","倒挂钩卡口"]""", "Cache stores distinct items with readable Chinese");
await database.Update<ImageAnalysisCache>().Set(x => x.RecognitionResult, "[]").Where(x => x.CacheKey == key).ExecuteAffrowsAsync();
var otherImage = Convert.ToBase64String(data.Append((byte)42).ToArray());
var hit = (await Inspect(otherImage, key)).GetProperty("data");
Check(hit.GetArrayLength() == 0, "Same client key reuses cached result for different image bytes");
await database.Update<ImageAnalysisCache>().Set(x => x.RecognitionResult, """{"text":"legacy","logoBrands":[]}""")
.Where(x => x.CacheKey == key).ExecuteAffrowsAsync();
Check((await Inspect(image, key)).GetProperty("data").Deserialize<string[]>()!.SequenceEqual(expected), "Refresh legacy cache");
Check((await Inspect(Convert.ToBase64String(new byte[30]), key)).GetProperty("code").GetInt32() != 200, "Invalid image denied");
Check((await Inspect("invalid!", key)).GetProperty("code").GetInt32() != 200, "Malformed Base64 denied before cache hit");
foreach (var invalid in new[] { "invalid", new string('z', 32), null })
{
var rejected = await Inspect(otherImage, invalid);
Check(!rejected.TryGetProperty("code", out var code) || code.GetInt32() != 200, "Reject missing or malformed MD5 before cache hit");
}
Console.WriteLine($"PASS {checks} HTTP and MySQL checks");
}
finally
{
await app.StopAsync();
await database.Delete<ImageAnalysisCache>().Where(x => x.CacheKey == key).ExecuteAffrowsAsync();
}
}
}
/// <summary>仅测试宿主使用的身份处理器,生产插件始终沿用宿主 Bearer 认证。</summary>
internal sealed class TestAuthentication(IOptionsMonitor<AuthenticationSchemeOptions> options, ILoggerFactory logger, UrlEncoder encoder)
: AuthenticationHandler<AuthenticationSchemeOptions>(options, logger, encoder)
{
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
{
var name = Request.Headers["X-Test-User"].ToString();
if (string.IsNullOrEmpty(name)) return Task.FromResult(AuthenticateResult.NoResult());
var principal = new ClaimsPrincipal(new ClaimsIdentity([new Claim(JwtClaimTypes.UserName, name)], Scheme.Name));
return Task.FromResult(AuthenticateResult.Success(new AuthenticationTicket(principal, Scheme.Name)));
}
}
/// <summary>返回模型协议示例,使 HTTP 检查无需外部密钥。</summary>
internal static class RecognitionEndpoint
{
private const string Content = """["\u6025\u901F\u53D1\u8D27","急速发货","螺旋伸缩","急速发货","金属挂钩","可调节","不挡扇叶","倒挂钩卡口"]""";
internal static async Task<IResult> RespondAsync(HttpRequest request, CancellationToken cancellationToken)
{
using var body = await JsonDocument.ParseAsync(request.Body, cancellationToken: cancellationToken);
var root = body.RootElement;
var parts = root.GetProperty("messages")[0].GetProperty("content");
if (root.GetProperty("model").GetString() != "test-vision"
|| request.Headers.Authorization.ToString() != "Bearer test-key"
|| root.GetProperty("stream").GetBoolean() || root.GetProperty("enable_thinking").GetBoolean()
|| !parts[0].GetProperty("image_url").GetProperty("url").GetString()!.StartsWith("data:image/png;base64,iVBOR")
|| !parts[1].GetProperty("text").GetString()!.Contains("JSON 字符串数组"))
throw new Exception("Invalid model request");
return Results.Json(new { choices = new[] { new { message = new { content = Content } } } });
}
}
@@ -0,0 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup><OutputType>Exe</OutputType><Nullable>enable</Nullable></PropertyGroup>
<ItemGroup><ProjectReference Include="../../Plugins/CloudProduct/Store.CloudProduct.csproj" /></ItemGroup>
</Project>
+39
View File
@@ -0,0 +1,39 @@
using System.Text.Json;
using Store.Modules.CloudProduct.Entities;
using var config = JsonDocument.Parse(File.ReadAllText("Plugins/CloudProduct/appsettings.json"));
var connection = Environment.GetEnvironmentVariable("Plugins__CloudProduct__ProductInspection__ConnectionString")
?? config.RootElement.GetProperty("ProductInspection").GetProperty("ConnectionString").GetString();
using var db = new FreeSql.FreeSqlBuilder().UseConnectionString(FreeSql.DataType.MySql, connection).Build();
const string tableQuery = "SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() ORDER BY TABLE_NAME";
const string columnsQuery = "SELECT COLUMN_NAME FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'image_analysis_cache' ORDER BY ORDINAL_POSITION";
if (args.Contains("--initialize"))
{
// 旧表只移除两个派生字段,保留缓存键、响应原文及更新时间。
var existing = await db.Ado.QueryAsync<string>(tableQuery);
if (!existing.Contains("image_analysis_cache")) db.CodeFirst.SyncStructure(typeof(ImageAnalysisCache));
var columns = await db.Ado.QueryAsync<string>(columnsQuery);
var oldResult = new[] { "FormattedData", "识别结果" }.SingleOrDefault(columns.Contains);
if (oldResult != null)
await db.Ado.ExecuteNonQueryAsync($"ALTER TABLE image_analysis_cache CHANGE COLUMN `{oldResult}` RecognitionResult LONGTEXT NOT NULL");
var drops = new[] { "DetectionText", "LogoBrands" }.Where(columns.Contains).Select(name => $"DROP COLUMN `{name}`").ToArray();
if (drops.Length > 0) await db.Ado.ExecuteNonQueryAsync("ALTER TABLE image_analysis_cache " + string.Join(", ", drops));
// 旧键不能还原为图片 MD5,禁止在有旧缓存的环境中直接缩短主键。
if (await db.Select<ImageAnalysisCache>().Where(x => x.CacheKey.Length > 32).AnyAsync())
throw new InvalidOperationException("请先归档或清理旧的 SHA-256 图片缓存,再执行升级。");
db.CodeFirst.SyncStructure(typeof(ImageAnalysisCache));
await db.Ado.ExecuteNonQueryAsync("DROP TABLE IF EXISTS inspection_task_item, inspection_task, inspection_result, inspection_user_rule");
}
var tables = await db.Ado.QueryAsync<string>(tableQuery);
Console.WriteLine(string.Join(", ", tables));
var cacheColumns = await db.Ado.QueryAsync<string>(columnsQuery);
Console.WriteLine("Cache columns: " + string.Join(", ", cacheColumns));
Console.WriteLine($"Cache rows: {await db.Select<ImageAnalysisCache>().CountAsync()}");
if (args.Contains("--schema")) return;
if (!cacheColumns.ToHashSet().SetEquals(new[] { "CacheKey", "RecognitionResult", "UpdatedAt" }))
throw new Exception("图片识别缓存结构不匹配。");
if (!tables.Contains("image_analysis_cache"))
throw new Exception("商品检测专用库缺少图片缓存表。");
var keyLength = await db.Ado.ExecuteScalarAsync("SELECT CHARACTER_MAXIMUM_LENGTH FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'image_analysis_cache' AND COLUMN_NAME = 'CacheKey'");
if (Convert.ToInt32(keyLength) != 32) throw new Exception("CacheKey 应为 32 位 MD5。");
await HttpChecks.RunAsync(db);
@@ -145,6 +145,35 @@ public sealed class PersistentSessionTests
Assert.NotNull(await service.ValidateTokenAsync(replacement.Token));
}
[Fact]
public async Task Cleanup_RemovesRevokedAndExpiredTokens_AndPreservesActiveTokens()
{
using var db = Open(":memory:");
using var cache = new MemoryCache(new MemoryCacheOptions());
var clock = new Clock();
var service = new TokenService(db, Options.Create(new TokenAuthOptions()), cache, clock);
var active = Issue(service);
Assert.NotNull(await service.ValidateTokenAsync(active.Token));
var now = DateTime.SpecifyKind(clock.Now.UtcDateTime, DateTimeKind.Unspecified);
// 覆盖撤销、闲置到期、绝对到期的等值边界,以及尚差一秒到期的有效记录。
db.Insert(new[]
{
new UserToken { UserName = "same", TokenHash = "revoked", CreatedAt = now, ExpiresAt = now.AddDays(7), Revoked = true },
new UserToken { UserName = "same", TokenHash = "idle", CreatedAt = now.AddDays(-7), ExpiresAt = now },
new UserToken { UserName = "same", TokenHash = "absolute", CreatedAt = now.AddDays(-30), ExpiresAt = now.AddDays(1) },
new UserToken { UserName = "same", TokenHash = "near-expiry", CreatedAt = now.AddDays(-30).AddSeconds(1), ExpiresAt = now.AddSeconds(1) }
}).ExecuteAffrows();
Assert.Equal(3, service.CleanupExpiredTokens());
Assert.Equal(2, db.Select<UserToken>().Count());
Assert.True(db.Select<UserToken>().Any(t => t.TokenHash == "near-expiry"));
Assert.Equal(0, service.CleanupExpiredTokens());
Assert.NotNull(await service.ValidateTokenAsync(active.Token));
clock.Now = clock.Now.AddSeconds(1);
Assert.Equal(1, service.CleanupExpiredTokens());
Assert.Single(db.Select<UserToken>().ToList());
}
[Fact]
public async Task CacheDisabled_ObservesExternalRevocation_AndRejectsIdleExpiry()
{
@@ -182,9 +182,9 @@ public sealed class UserManagementTests
.Set(u => u.SyncLogisticsPerOrder, 0.5m).Where(u => u.Id == context.Main.Id).ExecuteAffrowsAsync();
var info = await context.Query.GetUser("child");
Assert.Equal("brand", info.OemId);
Assert.Equal(2.2m, info.PostagePerOrder);
Assert.Equal(2.5m, info.RefundPostagePerOrder);
Assert.Equal(0m, info.GiftOemAmountPerOrder);
Assert.Equal(1m, info.PostagePerOrder);
Assert.Equal(1m, info.RefundPostagePerOrder);
Assert.Equal(-1m, info.GiftOemAmountPerOrder);
Assert.Equal(0.5m, info.SyncLogisticsPerOrder);
await context.Db.Update<UserEntity>().Set(u => u.Authority, "订单").Where(u => u.Id == context.Main.Id).ExecuteAffrowsAsync();
Assert.DoesNotContain("积分用户", (await context.Query.GetUser("child")).Authority);
@@ -0,0 +1,61 @@
using MAX.Framework.Commons;
using Store.Users.Entities;
using Store.Users.Repositories;
using Store.Users.Services;
namespace Store.Users.Tests;
/// <summary>验证主账号解析及无效父账号的继承边界。</summary>
public sealed class UserRepositoryTests
{
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task ChildFees_MatchMainAccount_IncludingUnsetValues(bool unset)
{
using var context = new UserTestContext();
decimal? fee = unset ? null : 0.5m;
await context.Db.Update<UserEntity>().Set(u => u.PostagePerOrder, fee)
.Set(u => u.RefundPostagePerOrder, fee).Set(u => u.GiftOemAmountPerOrder, fee)
.Set(u => u.SyncLogisticsPerOrder, fee).Set(u => u.ShopPointsPerMonth, 45)
.Where(u => u.Id == context.Main.Id).ExecuteAffrowsAsync();
var main = await context.Query.GetUser("main");
var child = await context.Query.GetUser("child");
Assert.Equal(main.PostagePerOrder, child.PostagePerOrder);
Assert.Equal(main.RefundPostagePerOrder, child.RefundPostagePerOrder);
Assert.Equal(main.GiftOemAmountPerOrder, child.GiftOemAmountPerOrder);
Assert.Equal(main.SyncLogisticsPerOrder, child.SyncLogisticsPerOrder);
Assert.Equal(45, child.ShopPointsPerMonth);
Assert.Equal(30, (await context.Read("child")).ShopPointsPerMonth);
}
[Theory]
[InlineData("main", "main")]
[InlineData("child", "main")]
[InlineData("missing", null)]
public async Task GetMainUser_ResolvesOwner(string userName, string? expected)
{
using var context = new UserTestContext();
var repository = (IUserRepository)Activator.CreateInstance(
typeof(UserManagementService).Assembly.GetType("Store.Users.Repositories.UserRepository", true)!, context.Db)!;
Assert.Equal(expected, (await repository.GetMainUser(userName))?.UserName);
}
[Theory]
[InlineData("missing")]
[InlineData("child")]
[InlineData("")]
public async Task InvalidParent_IsRejectedByBothQueries(string parent)
{
using var context = new UserTestContext();
await context.Db.Update<UserEntity>().Set(u => u.ParentUserName, parent)
.Where(u => u.Id == context.Child.Id).ExecuteAffrowsAsync();
var repository = (IUserRepository)Activator.CreateInstance(
typeof(UserManagementService).Assembly.GetType("Store.Users.Repositories.UserRepository", true)!, context.Db)!;
await Assert.ThrowsAsync<AppException>(() => repository.GetUser("child"));
await Assert.ThrowsAsync<AppException>(() => repository.GetMainUser("child"));
}
}
+1 -1
View File
@@ -50,7 +50,7 @@ try
actor.UserName = main.UserName;
var sub = await users.Create(new() { UserName = "child", Password = "child-password", Authority = "积分用户" }, true, default);
Assert(sub.ParentUserName == main.UserName && sub.OemId == main.OemId, "子账号归属或OEM继承错误");
Assert(sub.PostagePerOrder == 2.2m && sub.RefundPostagePerOrder == 2.5m, "继承费用下限错误");
Assert(sub.PostagePerOrder == main.PostagePerOrder && sub.RefundPostagePerOrder == main.RefundPostagePerOrder, "子账号费用应与主账号一致");
await Reject(() => users.Create(new() { UserName = "bad", Password = "password", Authority = "超级权限" }, true, default));
await Reject(() => users.Create(new() { UserName = "bad-admin", Password = "password", SaLevel = 1 }, true, default));
await Reject(() => users.Update(sub.Id, new() { ShopPointsPerMonth = 30 }, true, default));