using System.Globalization; using System.Security.Claims; using System.Text.Json; using Admin.NET.Core; using Admin.NET.Plugin.AiDOP.Controllers; using Admin.NET.Plugin.AiDOP.DataPlatform; using Admin.NET.Plugin.AiDOP.DataPlatform.FileImport; using Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress; using Admin.NET.Plugin.AiDOP.Entity.DataPlatform; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging.Abstractions; using SqlSugar; using Xunit; namespace Admin.NET.Plugin.AiDOP.Tests.DataPlatform; public sealed class MdpSourceTenantScopeTests : IDisposable { private const long OwnTenant = 101; private const long OtherTenant = 202; private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web); private readonly SqlSugarClient _db = new(new ConnectionConfig { DbType = DbType.Sqlite, ConnectionString = "Data Source=:memory:", InitKeyType = InitKeyType.Attribute }); public MdpSourceTenantScopeTests() { _db.Ado.Open(); _db.Ado.ExecuteCommand(""" CREATE TABLE mdp_source ( id INTEGER PRIMARY KEY, tenant_id INTEGER, source_code TEXT, system_code TEXT, source_name TEXT, source_type TEXT, conn_mode TEXT, status INTEGER, db_type TEXT, db_host TEXT, db_port INTEGER, db_name TEXT, db_user TEXT, db_password_enc TEXT, db_extra_params TEXT, api_base_url TEXT, api_auth_type TEXT, api_auth_config TEXT, last_health_check TEXT, health_status INTEGER, health_msg TEXT, remark TEXT, create_time TEXT, update_time TEXT, UNIQUE (tenant_id, source_code) ) """); _db.Ado.ExecuteCommand("CREATE TABLE SysTenant (Id INTEGER PRIMARY KEY, Title TEXT)"); _db.Ado.ExecuteCommand("INSERT INTO SysTenant VALUES (101,'A'), (202,'B')"); _db.Ado.ExecuteCommand("CREATE TABLE mdp_tenant_std_source (tenant_id INTEGER, source_system TEXT, std_object TEXT)"); _db.Ado.ExecuteCommand("INSERT INTO mdp_tenant_std_source VALUES (101,'SHARED','PURCHASE'), (202,'SHARED','SUPPLIER')"); _db.Insertable(new[] { Source(0, "BUILTIN"), Source(OtherTenant, "FOREIGN"), Source(OtherTenant, "DUPLICATE", "FOREIGN-SYSTEM"), Source(OwnTenant, "DUPLICATE", "OWN-SYSTEM"), Source(OwnTenant, "OWNSOURCE", "SHARED"), Source(OwnTenant, "ONLY-FOREIGN-BINDING", "FOREIGN-REGISTRATION") }).ExecuteCommand(); _db.Ado.ExecuteCommand("INSERT INTO mdp_tenant_std_source VALUES (202,'FOREIGN-REGISTRATION','WAREHOUSE')"); } [Theory] [InlineData(AccountTypeEnum.SysAdmin, 3)] [InlineData(AccountTypeEnum.NormalUser, 3)] [InlineData(AccountTypeEnum.SuperAdmin, 6)] public async Task ListRespectsTenantBoundaryAndPreservesPlatformAccess(AccountTypeEnum accountType, int expectedCount) { var response = JsonSerializer.SerializeToElement(await Service(accountType).GetList(null, "API_INBOUND"), JsonOptions); var rows = response.GetProperty("list").EnumerateArray().ToArray(); var ids = rows.Select(row => row.GetProperty("tenantId").GetInt64()).Distinct().Order(); Assert.Equal(accountType == AccountTypeEnum.SuperAdmin ? [0L, OwnTenant, OtherTenant] : [OwnTenant], ids); Assert.Equal(expectedCount, rows.Length); } [Fact] public async Task SysAdminCannotTestOrDisableForeignOrBuiltInSources() { var service = Service(AccountTypeEnum.SysAdmin); foreach (var code in new[] { "FOREIGN", "BUILTIN" }) { await Reject(() => service.Test(code), "未找到来源"); await Reject(() => service.Bindings(code), "未找到来源"); await Reject(() => service.Disable(code, new() { Confirm = true }), "未找到来源"); } Assert.Equal(2, await _db.Queryable().CountAsync(source => source.SourceCode != "DUPLICATE" && source.TenantId != OwnTenant && source.Status == 1)); } [Theory] [InlineData(AccountTypeEnum.SysAdmin)] [InlineData(AccountTypeEnum.NormalUser)] public async Task SourceCodeIsResolvedInsideTenantBeforeLookup(AccountTypeEnum accountType) { var service = Service(accountType); var response = JsonSerializer.SerializeToElement(await service.Bindings("DUPLICATE"), JsonOptions); Assert.Equal("OWN-SYSTEM", response.GetProperty("systemCode").GetString()); await service.Disable("DUPLICATE", new() { Confirm = true }); var rows = await _db.Queryable().Where(source => source.SourceCode == "DUPLICATE") .OrderBy(source => source.TenantId).ToListAsync(); Assert.Equal(new[] { 0, 1 }, rows.Select(row => row.Status)); } [Fact] public async Task BindingPreviewAndDisableConfirmationOmitForeignBindingDetails() { var service = Service(AccountTypeEnum.SysAdmin); var preview = JsonSerializer.SerializeToElement(await service.Bindings("OWNSOURCE"), JsonOptions); var binding = Assert.Single(preview.GetProperty("bindings").EnumerateArray()); Assert.Equal(OwnTenant, binding.GetProperty("tenantId").GetInt64()); Assert.Equal("PURCHASE", binding.GetProperty("stdObject").GetString()); var confirmation = JsonSerializer.SerializeToElement(await service.Disable("ONLY-FOREIGN-BINDING", new()), JsonOptions); Assert.True(confirmation.GetProperty("needConfirm").GetBoolean()); Assert.Empty(confirmation.GetProperty("bindings").EnumerateArray()); var foreignOnlyPreview = JsonSerializer.SerializeToElement(await service.Bindings("ONLY-FOREIGN-BINDING"), JsonOptions); Assert.True(foreignOnlyPreview.GetProperty("needConfirm").GetBoolean()); Assert.Empty(foreignOnlyPreview.GetProperty("bindings").EnumerateArray()); } [Theory] [InlineData(AccountTypeEnum.SysAdmin)] [InlineData(AccountTypeEnum.NormalUser)] public async Task MissingTenantCannotUseBuiltInNamespace(AccountTypeEnum accountType) { var response = JsonSerializer.SerializeToElement(await Service(accountType, tenantId: 0).GetList(null, null), JsonOptions); Assert.Empty(response.GetProperty("list").EnumerateArray()); } [Fact] public async Task ExcelSourcesOnManagementPageAreTenantScopedWhileImportKeepsPublicTemplates() { await _db.Ado.ExecuteCommandAsync(""" INSERT INTO mdp_source (id, tenant_id, source_code, source_type, status) VALUES (10,0,'TEMPLATE','FILE_EXCEL',1), (11,101,'OWN-FILE','FILE_EXCEL',1), (12,202,'FOREIGN-FILE','FILE_EXCEL',1) """); await _db.Ado.ExecuteCommandAsync(""" CREATE TABLE mdp_entity (id INTEGER PRIMARY KEY, tenant_id INTEGER, source_id INTEGER, status INTEGER, entity_code TEXT, entity_name TEXT, target_table_name TEXT, biz_key_expr TEXT, is_public_template INTEGER) """); await _db.Ado.ExecuteCommandAsync(""" INSERT INTO mdp_entity VALUES (1,0,10,1,'PUBLIC','公共导入模板',NULL,NULL,1), (2,101,11,1,'OWN','本租户模板',NULL,NULL,0), (3,202,12,1,'FOREIGN','其他租户模板',NULL,NULL,0), (4,202,11,1,'FOREIGN-PUBLIC','其他租户的公共模板',NULL,NULL,1) """); var service = new MdpExcelImportService(_db, User(AccountTypeEnum.SysAdmin, OwnTenant), null, null, []); var controller = new MdpFileImportController(service); var management = await controller.Entities(default, forSourceManagement: true); Assert.Equal(new[] { "OWN" }, Codes(management)); var import = await controller.Entities(default); Assert.Equal(new[] { "FOREIGN-PUBLIC", "OWN", "PUBLIC" }, Codes(import)); static IEnumerable Codes(object response) => JsonSerializer.SerializeToElement(response, JsonOptions) .GetProperty("list").EnumerateArray().Select(row => row.GetProperty("entityCode").GetString()).Order(); } private MdpSourceConfigService Service(AccountTypeEnum accountType, long tenantId = OwnTenant) { var passwords = new MdpSourcePasswordResolver(); return new MdpSourceConfigService(_db, User(accountType, tenantId), new MdpSourceScopeFactory(_db, passwords), passwords, NullLogger.Instance, new MdpApiPullEgress(new ConfigurationBuilder().Build())); } private static UserManager User(AccountTypeEnum accountType, long tenantId) { var identity = new ClaimsIdentity([ new(ClaimConst.TenantId, tenantId.ToString(CultureInfo.InvariantCulture)), new(ClaimConst.AccountType, ((int)accountType).ToString(CultureInfo.InvariantCulture)) ], "Test"); return new UserManager(new HttpContextAccessor { HttpContext = new DefaultHttpContext { User = new ClaimsPrincipal(identity) } }); } private static MdpSource Source(long tenant, string code, string system = null) => new() { TenantId = tenant, SourceCode = code, SourceName = code, SourceType = "API_INBOUND", SystemCode = system, CreateTime = DateTime.UtcNow, UpdateTime = DateTime.UtcNow }; private static async Task Reject(Func act, string expectedMessage) { var error = await Record.ExceptionAsync(act); Assert.NotNull(error); Assert.Contains(expectedMessage, error.Message, StringComparison.Ordinal); } public void Dispose() => _db.Dispose(); }