Open-source eCommerce platform for C# and ASP.NET Core 10 with MongoDB. Build multi-store shops and multi-vendor marketplaces with B2B/B2C, REST API, plugins, Vue 3 and Docker.
C# aspnet-corecsharpdockerdotnetecommerceecommerce-platformmongodbmulti-storemulti-vendornosqlonline-shopshoppingcart
Fix Task 7 review findings: scope DeleteSelected, add CanView for Store's looser view/copy rule (ARCH-001 Phase 1)
KrzysztofPajak35dd5d9892b3
diff --git a/src/Tests/Grand.Web.Admin.Tests/Controllers/BaseProductControllerTests.cs b/src/Tests/Grand.Web.Admin.Tests/Controllers/BaseProductControllerTests.csindex 1730311be..0ead37cff 100644--- a/src/Tests/Grand.Web.Admin.Tests/Controllers/BaseProductControllerTests.cs+++ b/src/Tests/Grand.Web.Admin.Tests/Controllers/BaseProductControllerTests.cs@@ -99,15 +99,15 @@ public class BaseProductControllerTestsvar redirect = result as RedirectToActionResult;Assert.IsNotNull(redirect);Assert.AreEqual("List", redirect.ActionName);- _scopeMock.Verify(s => s.HasAccess(It.IsAny<Product>()), Times.Never);+ _scopeMock.Verify(s => s.CanView(It.IsAny<Product>()), Times.Never);}[TestMethod]- public async Task EditGet_ScopeDeniesAccess_RedirectsToList()+ public async Task EditGet_ScopeDeniesView_RedirectsToList(){var product = new Product { Id = "p1" };_productServiceMock.Setup(p => p.GetProductById("p1", true)).ReturnsAsync(product);- _scopeMock.Setup(s => s.HasAccess(product)).ReturnsAsync(false);+ _scopeMock.Setup(s => s.CanView(product)).ReturnsAsync(false);var result = await _controller.Edit("p1");@@ -120,11 +120,11 @@ public class BaseProductControllerTests}[TestMethod]- public async Task EditGet_ScopeGrantsAccess_ShowsForm()+ public async Task EditGet_ScopeGrantsView_ShowsForm(){var product = new Product { Id = "p1" };_productServiceMock.Setup(p => p.GetProductById("p1", true)).ReturnsAsync(product);- _scopeMock.Setup(s => s.HasAccess(product)).ReturnsAsync(true);+ _scopeMock.Setup(s => s.CanView(product)).ReturnsAsync(true);var result = await _controller.Edit("p1");@@ -133,6 +133,23 @@ public class BaseProductControllerTestss => s.PrepareProductModel(It.IsAny<ProductModel>(), product, false, false), Times.Once);}+ [TestMethod]+ public async Task EditGet_UsesCanViewNotHasAccess_LooserRuleWins()+ {+ // Regression guard for the review fix: Edit(GET) must gate on the looser CanView, not the+ // strict mutation-only HasAccess. A product HasAccess would deny (e.g. Store's multi-store+ // rule) but CanView allows must still show the form.+ var product = new Product { Id = "p1" };+ _productServiceMock.Setup(p => p.GetProductById("p1", true)).ReturnsAsync(product);+ _scopeMock.Setup(s => s.HasAccess(product)).ReturnsAsync(false);+ _scopeMock.Setup(s => s.CanView(product)).ReturnsAsync(true);++ var result = await _controller.Edit("p1");++ Assert.IsInstanceOfType<ViewResult>(result);+ _scopeMock.Verify(s => s.HasAccess(It.IsAny<Product>()), Times.Never);+ }+// --- Edit (POST) -------------------------------------------------------------------------------[TestMethod]@@ -232,11 +249,11 @@ public class BaseProductControllerTests// --- CopyProduct -----------------------------------------------------------------------------------[TestMethod]- public async Task CopyProduct_ScopeDeniesAccess_RedirectsToListWithoutCopying()+ public async Task CopyProduct_ScopeDeniesView_RedirectsToListWithoutCopying(){var originalProduct = new Product { Id = "p1" };_productServiceMock.Setup(p => p.GetProductById("p1", true)).ReturnsAsync(originalProduct);- _scopeMock.Setup(s => s.HasAccess(originalProduct)).ReturnsAsync(false);+ _scopeMock.Setup(s => s.CanView(originalProduct)).ReturnsAsync(false);var copyProductServiceMock = new Mock<ICopyProductService>();var model = new ProductModel {@@ -253,12 +270,12 @@ public class BaseProductControllerTests}[TestMethod]- public async Task CopyProduct_ScopeGrantsAccess_Copies()+ public async Task CopyProduct_ScopeGrantsView_Copies(){var originalProduct = new Product { Id = "p1" };var newProduct = new Product { Id = "p2" };_productServiceMock.Setup(p => p.GetProductById("p1", true)).ReturnsAsync(originalProduct);- _scopeMock.Setup(s => s.HasAccess(originalProduct)).ReturnsAsync(true);+ _scopeMock.Setup(s => s.CanView(originalProduct)).ReturnsAsync(true);var copyProductServiceMock = new Mock<ICopyProductService>();copyProductServiceMock.Setup(s => s.CopyProduct(originalProduct, "copy", false)).ReturnsAsync(newProduct);@@ -274,6 +291,75 @@ public class BaseProductControllerTestsAssert.AreEqual("p2", redirect.RouteValues["id"]);}+ [TestMethod]+ public async Task CopyProduct_UsesCanViewNotHasAccess_LooserRuleWins()+ {+ // Regression guard: CopyProduct must gate on CanView (Store's original rule: denies only+ // when LimitedToStores excludes the staff store), not the strict HasAccess.+ var originalProduct = new Product { Id = "p1" };+ var newProduct = new Product { Id = "p2" };+ _productServiceMock.Setup(p => p.GetProductById("p1", true)).ReturnsAsync(originalProduct);+ _scopeMock.Setup(s => s.HasAccess(originalProduct)).ReturnsAsync(false);+ _scopeMock.Setup(s => s.CanView(originalProduct)).ReturnsAsync(true);+ var copyProductServiceMock = new Mock<ICopyProductService>();+ copyProductServiceMock.Setup(s => s.CopyProduct(originalProduct, "copy", false)).ReturnsAsync(newProduct);++ var model = new ProductModel {+ CopyProductModel = new CopyProductModel { Id = "p1", Name = "copy", Published = false, CopyImages = false }+ };++ var result = await _controller.CopyProduct(model, copyProductServiceMock.Object, new Mock<IPictureService>().Object);++ var redirect = result as RedirectToActionResult;+ Assert.IsNotNull(redirect);+ Assert.AreEqual("Edit", redirect.ActionName);+ Assert.AreEqual("p2", redirect.RouteValues["id"]);+ }++ // --- DeleteSelected ------------------------------------------------------------------------------++ [TestMethod]+ public async Task DeleteSelected_NoIds_DoesNotCallService()+ {+ var result = await _controller.DeleteSelected(new List<string>());++ var json = result as JsonResult;+ Assert.IsNotNull(json);+ _productViewModelServiceMock.Verify(s => s.DeleteSelected(It.IsAny<List<string>>()), Times.Never);+ }++ [TestMethod]+ public async Task DeleteSelected_FiltersOutProductsScopeDenies()+ {+ // Regression guard for the review fix: DeleteSelected is a mutation, so it must filter through+ // the strict HasAccess before delegating - without this, Store would gain an unscoped+ // bulk-delete endpoint (any staff could delete any product id in the system).+ var owned = new Product { Id = "owned" };+ var foreign = new Product { Id = "foreign" };+ _productServiceMock.Setup(p => p.GetProductsByIds(new[] { "owned", "foreign" }, true))+ .ReturnsAsync(new List<Product> { owned, foreign });+ _scopeMock.Setup(s => s.HasAccess(owned)).ReturnsAsync(true);+ _scopeMock.Setup(s => s.HasAccess(foreign)).ReturnsAsync(false);++ await _controller.DeleteSelected(new List<string> { "owned", "foreign" });++ _productViewModelServiceMock.Verify(+ s => s.DeleteSelected(It.Is<List<string>>(ids => ids.Count == 1 && ids[0] == "owned")), Times.Once);+ }++ [TestMethod]+ public async Task DeleteSelected_AllProductsScopeDenies_DoesNotCallDeleteSelected()+ {+ var foreign = new Product { Id = "foreign" };+ _productServiceMock.Setup(p => p.GetProductsByIds(new[] { "foreign" }, true))+ .ReturnsAsync(new List<Product> { foreign });+ _scopeMock.Setup(s => s.HasAccess(foreign)).ReturnsAsync(false);++ await _controller.DeleteSelected(new List<string> { "foreign" });++ _productViewModelServiceMock.Verify(s => s.DeleteSelected(It.IsAny<List<string>>()), Times.Never);+ }+// --- GoToSku -----------------------------------------------------------------------------------------// Deliberate behavior tightening vs. Store's pre-refactor GoToSku (see the TODO in// BaseProductController.GoToSku): denial now redirects to List, not Edit.diff --git a/src/Tests/Grand.Web.Store.Tests/Services/StoreAdminDataScopeTests.cs b/src/Tests/Grand.Web.Store.Tests/Services/StoreAdminDataScopeTests.csindex 83ccf508f..0b3f56b47 100644--- a/src/Tests/Grand.Web.Store.Tests/Services/StoreAdminDataScopeTests.cs+++ b/src/Tests/Grand.Web.Store.Tests/Services/StoreAdminDataScopeTests.cs@@ -82,4 +82,32 @@ public class StoreAdminDataScopeTestsvar scope = new StoreAdminDataScope<Product>(_contextAccessor.Object);Assert.AreEqual("Admin", scope.ResourceKeyPrefix);}++ // CanView is deliberately looser than HasAccess: it mirrors Store's original Edit(GET)/CopyProduct+ // rule (a global or multi-store product including the staff member's store may be viewed/copied;+ // only a product limited to stores that exclude the staff member's store is denied). See the+ // existing test comment in ProductControllerTests.EditGet_ProductSharedAcrossMultipleStoresIncludingStaffStore_ShowsFormWithWarning:+ // "This is the one path that must stay outside any shared 'authorize or redirect' helper."+ [TestMethod]+ public async Task CanView_ProductNotLimitedToStores_ReturnsTrue()+ {+ var scope = new StoreAdminDataScope<Product>(_contextAccessor.Object);+ Assert.IsTrue(await scope.CanView(new Product { LimitedToStores = false }));+ }++ [TestMethod]+ public async Task CanView_ProductInMultipleStoresIncludingStaffStore_ReturnsTrue()+ {+ var scope = new StoreAdminDataScope<Product>(_contextAccessor.Object);+ var product = new Product { LimitedToStores = true, Stores = [StaffStoreId, "store-3"] };+ Assert.IsTrue(await scope.CanView(product));+ }++ [TestMethod]+ public async Task CanView_ProductLimitedToOtherStore_ReturnsFalse()+ {+ var scope = new StoreAdminDataScope<Product>(_contextAccessor.Object);+ var product = new Product { LimitedToStores = true, Stores = ["store-2"] };+ Assert.IsFalse(await scope.CanView(product));+ }}diff --git a/src/Web/Grand.Web.AdminShared/Controllers/BaseProductController.cs b/src/Web/Grand.Web.AdminShared/Controllers/BaseProductController.csindex a20b0c64e..4f1ba75a4 100644--- a/src/Web/Grand.Web.AdminShared/Controllers/BaseProductController.cs+++ b/src/Web/Grand.Web.AdminShared/Controllers/BaseProductController.cs@@ -28,27 +28,37 @@ using Microsoft.AspNetCore.StaticFiles;namespace Grand.Web.AdminShared.Controllers;-// Resource-key-prefix audit (2026-08-16, ARCH-001 Phase 1 Task 6, corrected after review):-// 28 unique "Admin.<suffix>"/"Vendor.<suffix>" GetResource(...) suffixes were found across-// Grand.Web.Admin/Controllers/ProductController.cs, Grand.Web.Store/Controllers/ProductController.cs,-// Grand.Web.Vendor/Controllers/ProductController.cs, Grand.Web.AdminShared/Services/ProductViewModelService.cs-// and Grand.Web.Vendor/Services/ProductViewModelService.cs (multi-line-aware extraction; the brief's-// original line-bound grep undercounted this at 23). Of the 28:-// - 22 are Templated: both an "Admin.<suffix>" and a "Vendor.<suffix>" call site exist, so these are-// safe to write as $"{scope.ResourceKeyPrefix}.<suffix>" - e.g. Catalog.Products.Added/Updated/Deleted,-// Catalog.Products.Fields.ChangedWarning, Catalog.Products.List.SkuNotFound, Common.All, Customers.Guest,-// and 15 more (see task-6-resource-prefix-table.md for the full list).-// - 6 are Admin-only literals with no Vendor call site (keep as literal "Admin.<suffix>", do not-// template): Catalog.Products.Permissions, Catalog.Products.Imported,-// Catalog.Products.List.SearchPublished.ShowOnHomePage, Catalog.Products.TierPrices.Fields.CustomerGroup.All,-// Catalog.Products.TierPrices.Fields.Store.All, Common.UploadFile.-// - 0 are host-specific-not-templated (every "Vendor.<suffix>" call site has a matching "Admin.<suffix>"-// one, so none needed a scope.ResourceKeyPrefix == "Vendor" special case).+// Resource-key-prefix audit (2026-08-16, ARCH-001 Phase 1 Task 6, corrected after review — see Task 6's+// ledger entry). Inlined in full here (not just referenced) since planning artifacts under .superpowers/+// are untracked and do not survive in the repo once this branch merges.+//+// Templated via {scope.ResourceKeyPrefix} (Admin.<suffix> and Vendor.<suffix> both exist) — 22:+// Common.All, Customers.Guest, Configuration.Tax.Settings.TaxCategories.None,+// Catalog.Products.Added, Catalog.Products.Updated, Catalog.Products.Deleted,+// Catalog.Products.Fields.ChangedWarning, Catalog.Products.Fields.DeliveryDate.None,+// Catalog.Products.Fields.Warehouse.None, Catalog.Products.Bids.CantDeleteWithOrder,+// Catalog.Products.List.SkuNotFound, Catalog.Products.List.SearchPublished.All,+// Catalog.Products.List.SearchPublished.PublishedOnly, Catalog.Products.List.SearchPublished.UnpublishedOnly,+// Catalog.Products.List.SearchPublished.MarkAsNew, Catalog.ProductReservations.CantDeleteWithOrder,+// Catalog.Products.Calendar.CannotChangeInterval,+// Catalog.Products.ProductAttributes.Attributes.ValidationRules.MinLength,+// Catalog.Products.ProductAttributes.Attributes.ValidationRules.MaxLength,+// Catalog.Products.ProductAttributes.Attributes.ValidationRules.FileAllowedExtensions,+// Catalog.Products.ProductAttributes.Attributes.ValidationRules.FileMaximumSize,+// Catalog.Products.ProductAttributes.Attributes.ValidationRules.DefaultValue.+//+// Admin-only literal (no Vendor equivalent call site; keep as literal "Admin.<suffix>") — 6:+// Catalog.Products.Permissions (Vendor has no Permissions-suffixed resource lookup anywhere - its+// permission-denied paths don't emit this message), Catalog.Products.List.SearchPublished.ShowOnHomePage,+// Catalog.Products.Imported, Catalog.Products.TierPrices.Fields.CustomerGroup.All,+// Catalog.Products.TierPrices.Fields.Store.All, Common.UploadFile.+//+// Host-specific, not templated — 0: none found; every "Vendor.<suffix>" call site has a matching+// "Admin.<suffix>" one, so nothing needs a scope.ResourceKeyPrefix == "Vendor" guard instead of templating.+//// Store makes no separate resource lookups at all - every Store call site uses the literal "Admin.*" key-// directly, which is what scope.ResourceKeyPrefix == "Admin" (StoreAdminDataScope) already produces.-// Within this region (list/create/edit/delete/CopyProduct), every suffix used-// (Catalog.Products.List.SkuNotFound, Catalog.Products.Added, Catalog.Products.Updated,-// Catalog.Products.Deleted, Catalog.Products.Fields.ChangedWarning) is in the Templated set above.+// directly (Store has no distinct resource set), consistent with StoreAdminDataScope.ResourceKeyPrefix+// returning "Admin".[PermissionAuthorize(PermissionSystemName.Products)]public abstract class BaseProductController(@@ -153,7 +163,10 @@ public abstract class BaseProductController(if (product == null) return RedirectToAction("List");EditWarningCheck(product);- if (!await scope.HasAccess(product)) return RedirectToAction("List");+ // CanView, not HasAccess: viewing a shared/global product is allowed on Store (with a warning+ // from EditWarningCheck above); only mutating one is restricted to the exclusive single-store+ // owner. See IAdminDataScope<TEntity>.CanView's doc comment and StoreAdminDataScope.CanView.+ if (!await scope.CanView(product)) return RedirectToAction("List");var model = product.ToModel(dateTimeService);if (scope.DefaultStoreId is not null) model.StoreId = scope.DefaultStoreId;@@ -234,7 +247,20 @@ public abstract class BaseProductController([HttpPost]public async Task<IActionResult> DeleteSelected(ICollection<string> selectedIds){- if (selectedIds != null) await productViewModelService.DeleteSelected(selectedIds.ToList());+ if (selectedIds == null || selectedIds.Count == 0) return Json(new { Result = true });++ // This is a mutation (bulk delete), so it uses the strict HasAccess, matching Edit(POST)/Delete+ // above — not a no-op pass-through to the service. Without this filter, Store gains an+ // unscoped bulk-delete endpoint (any store staff could delete any product id in the system,+ // bypassing AccessToEntityByStore entirely) purely because MVC routes actions regardless of+ // whether a host's views ever link to them.+ var products = await productService.GetProductsByIds(selectedIds.ToArray(), true);+ var allowedIds = new List<string>();+ foreach (var product in products)+ if (await scope.HasAccess(product))+ allowedIds.Add(product.Id);++ if (allowedIds.Count > 0) await productViewModelService.DeleteSelected(allowedIds);return Json(new { Result = true });}@@ -247,7 +273,10 @@ public abstract class BaseProductController(try{var originalProduct = await productService.GetProductById(copyModel.Id, true);- if (!await scope.HasAccess(originalProduct)) return RedirectToAction("List");+ // CanView, not HasAccess: Store's original CopyProduct denies only when LimitedToStores is+ // true AND the staff member's store isn't among them — the same looser rule as Edit(GET)+ // above, not the strict mutation rule. See IAdminDataScope<TEntity>.CanView.+ if (!await scope.CanView(originalProduct)) return RedirectToAction("List");if (scope.DefaultStoreId is not null){diff --git a/src/Web/Grand.Web.AdminShared/Interfaces/IAdminDataScope.cs b/src/Web/Grand.Web.AdminShared/Interfaces/IAdminDataScope.csindex e64f6b381..9f50b84ab 100644--- a/src/Web/Grand.Web.AdminShared/Interfaces/IAdminDataScope.cs+++ b/src/Web/Grand.Web.AdminShared/Interfaces/IAdminDataScope.cs@@ -9,9 +9,18 @@ namespace Grand.Web.AdminShared.Interfaces;/// </summary>public interface IAdminDataScope<TEntity>{- /// <summary>Whether the current user may access this specific, already-loaded entity.</summary>+ /// <summary>Whether the current user may mutate (edit/delete) this specific, already-loaded entity.+ /// This is the strict check — for Store, matches AclMappingExtension.AccessToEntityByStore exactly+ /// (denies global and multi-store entities, only the entity's exclusive single store passes).</summary>Task<bool> HasAccess(TEntity entity);+ /// <summary>Whether the current user may view/reference this entity (open its edit form, copy it) —+ /// looser than <see cref="HasAccess"/> for hosts where viewing a shared/global entity is allowed but+ /// mutating it isn't. Defaults to <see cref="HasAccess"/> for hosts with no such split (Admin: always+ /// true either way; Vendor: the two are identical, verified against the existing, unsplit+ /// `CheckAccessToProduct`). Only Store overrides this.</summary>+ Task<bool> CanView(TEntity entity) => HasAccess(entity);+/// <summary>Narrows a query to the entities the current user may see. No-op for global (Admin) scope.</summary>IQueryable<TEntity> ApplyScope(IQueryable<TEntity> query);diff --git a/src/Web/Grand.Web.AdminShared/Services/StoreAdminDataScope.cs b/src/Web/Grand.Web.AdminShared/Services/StoreAdminDataScope.csindex 9105c91f9..6e5848922 100644--- a/src/Web/Grand.Web.AdminShared/Services/StoreAdminDataScope.cs+++ b/src/Web/Grand.Web.AdminShared/Services/StoreAdminDataScope.cs@@ -17,6 +17,18 @@ public class StoreAdminDataScope<TEntity>(IContextAccessor contextAccessor) : IAreturn Task.FromResult(entity != null && entity.AccessToEntityByStore(staffStoreId));}+ /// <summary>Looser than <see cref="HasAccess"/>: a global entity or one shared across multiple+ /// stores (including the staff member's) may be viewed; only an entity limited to stores that+ /// exclude the staff member's store is denied. Mirrors Store's original Edit(GET)/CopyProduct+ /// behavior (see Grand.Web.Store's ProductController pre-consolidation).</summary>+ public Task<bool> CanView(TEntity entity)+ {+ if (entity is null) return Task.FromResult(false);+ var staffStoreId = contextAccessor.WorkContext.CurrentCustomer.StaffStoreId;+ var allowed = !entity.LimitedToStores || entity.Stores.Contains(staffStoreId);+ return Task.FromResult(allowed);+ }+public IQueryable<TEntity> ApplyScope(IQueryable<TEntity> query){var staffStoreId = contextAccessor.WorkContext.CurrentCustomer.StaffStoreId;