From 1753e4bebcbda2642a356667818d4ef85ef9dd9f Mon Sep 17 00:00:00 2001 From: Andy Butland Date: Fri, 9 Oct 2026 13:05:23 +0100 Subject: [PATCH 1/4] Content Types: Refresh composing types when a property is added to a composition (closes #24117) (#24126) * Refresh composing content types when a property is added. Adding a property to a content type used as a composition left every type composed of (or inheriting from) it serving a published content type built before the property existed, so the value read as null on the front end and in Preview until the application restarted. ComposeContentTypeChanges only propagated to deriving types for changes in hasPropertyMainImpact, which never included a property addition. The deriving types therefore got no change entry at all, and neither the published content type cache nor the converted content cache was ever cleared for them. Propagation now also runs for a property addition, emitting RefreshOther for the deriving types - enough to clear both caches, without the cmsContentNu rebuild a pure addition does not need. The traversal is also made transitive (GetComposedOfTransitive), so a change reaches types further down an inheritance or composition chain rather than only the direct consumers. Reloading the published caches now clears IPublishedContentTypeCache as well, so "Reload Memory Cache" can recover a site left in this state instead of the rebuilt content being projected through the same stale definitions. * fix(core): propagate an alias change to deriving types, and address review A content type's published content type resolves its composition aliases recursively through its compositions, so renaming a content type left every type deriving from it reporting the old alias - breaking IsComposedOf on the front end and CompositionSchemaIds in the Delivery API - until another refresh or a restart. hasAliasChanged now propagates too; deriving types take RefreshOther, since the stored blob is keyed by property alias rather than content type alias and so needs no rebuild. GetComposedOfTransitive built its reverse edges by rescanning every content type for each type it found, making a base-type save O(types x descendants). It now builds the reverse lookup once, as GetPropertyAliasesReservedByDescendants does, so the traversal is O(types + composition edges). Also: name the target in both ContentCacheRefresher obsolete messages so the migration path is unambiguous when two of them are present, and assert in ReloadPublishedCacheTests that a cache hit re-serves the same instance, so the reference comparison after the reload cannot pass vacuously. Co-Authored-By: Claude Opus 5 (1M context) * Include a few more test scenarios for chained inheritance * For batched updates: Only load the content types once, and ensure that multiple saves (in)directly affecting the same content type only yield a single change --------- Co-authored-by: Claude Opus 5 (1M context) Co-authored-by: kjac --- .../Implement/ContentCacheRefresher.cs | 57 ++++++- ...ntentTypeServiceBase{TRepository,TItem}.cs | 144 ++++++++++++++---- .../Cache/PublishedContentTypeCacheTests.cs | 89 +++++++++++ .../Cache/ReloadPublishedCacheTests.cs | 49 ++++++ .../ContentTypeEditingServiceTests.Update.cs | 128 +++++++++++++++- .../DocumentHybridCacheDocumentTypeTests.cs | 75 +++++++++ .../ContentCacheRefresherIdKeyMapTests.cs | 3 +- 7 files changed, 504 insertions(+), 41 deletions(-) create mode 100644 tests/Umbraco.Tests.Integration/Umbraco.Core/Cache/ReloadPublishedCacheTests.cs diff --git a/src/Umbraco.Core/Cache/Refreshers/Implement/ContentCacheRefresher.cs b/src/Umbraco.Core/Cache/Refreshers/Implement/ContentCacheRefresher.cs index 038edd448b52..abe0a22b2ba7 100644 --- a/src/Umbraco.Core/Cache/Refreshers/Implement/ContentCacheRefresher.cs +++ b/src/Umbraco.Core/Cache/Refreshers/Implement/ContentCacheRefresher.cs @@ -38,11 +38,12 @@ public sealed class ContentCacheRefresher : PayloadCacheRefresherBase /// Initializes a new instance of the class. /// - [Obsolete("Please use the constructor taking all parameters. Scheduled for removal in Umbraco 19.")] + [Obsolete("Please use the constructor also taking IPublishedContentTypeCache. Scheduled for removal in Umbraco 19.")] public ContentCacheRefresher( AppCaches appCaches, IJsonSerializer serializer, @@ -73,13 +74,15 @@ public ContentCacheRefresher( contentService, publishStatusManagementService, documentCacheService, - cacheManager) + cacheManager, + StaticServiceProvider.Instance.GetRequiredService()) { } /// /// Initializes a new instance of the class. /// + [Obsolete("Please use the constructor also taking IPublishedContentTypeCache. Scheduled for removal in Umbraco 19.")] public ContentCacheRefresher( AppCaches appCaches, IJsonSerializer serializer, @@ -96,6 +99,46 @@ public ContentCacheRefresher( IPublishStatusManagementService publishStatusManagementService, IDocumentCacheService documentCacheService, ICacheManager cacheManager) + : this( + appCaches, + serializer, + idKeyMap, + domainService, + eventAggregator, + factory, + documentUrlService, + documentUrlAliasService, + domainCacheService, + documentNavigationQueryService, + documentNavigationManagementService, + contentService, + publishStatusManagementService, + documentCacheService, + cacheManager, + StaticServiceProvider.Instance.GetRequiredService()) + { + } + + /// + /// Initializes a new instance of the class. + /// + public ContentCacheRefresher( + AppCaches appCaches, + IJsonSerializer serializer, + IIdKeyMap idKeyMap, + IDomainService domainService, + IEventAggregator eventAggregator, + ICacheRefresherNotificationFactory factory, + IDocumentUrlService documentUrlService, + IDocumentUrlAliasService documentUrlAliasService, + IDomainCacheService domainCacheService, + IDocumentNavigationQueryService documentNavigationQueryService, + IDocumentNavigationManagementService documentNavigationManagementService, + IContentService contentService, + IPublishStatusManagementService publishStatusManagementService, + IDocumentCacheService documentCacheService, + ICacheManager cacheManager, + IPublishedContentTypeCache publishedContentTypeCache) : base(appCaches, serializer, eventAggregator, factory) { _idKeyMap = idKeyMap; @@ -108,6 +151,7 @@ public ContentCacheRefresher( _contentService = contentService; _documentCacheService = documentCacheService; _publishStatusManagementService = publishStatusManagementService; + _publishedContentTypeCache = publishedContentTypeCache; // TODO: Ideally we should inject IElementsCache // this interface is in infrastructure, and changing this is very breaking @@ -193,6 +237,15 @@ public override void RefreshInternal(JsonPayload[] payloads) /// public override void Refresh(JsonPayload[] payloads) { + // A "refresh all" is the signal that the in-memory published caches are being rebuilt from the database + // cache. Published content types are cached independently of the content they describe, so they have to + // be dropped here too - otherwise the rebuilt content is projected through the same definitions as + // before and the reload has no effect on anything the content type governs. + if (payloads.Any(x => x.ChangeTypes.HasType(TreeChangeTypes.RefreshAll))) + { + _publishedContentTypeCache.ClearAll(); + } + var idsRemoved = new HashSet(); foreach (JsonPayload payload in payloads) diff --git a/src/Umbraco.Core/Services/ContentTypeServiceBase{TRepository,TItem}.cs b/src/Umbraco.Core/Services/ContentTypeServiceBase{TRepository,TItem}.cs index baecae687d8f..b1a2906c3459 100644 --- a/src/Umbraco.Core/Services/ContentTypeServiceBase{TRepository,TItem}.cs +++ b/src/Umbraco.Core/Services/ContentTypeServiceBase{TRepository,TItem}.cs @@ -344,12 +344,13 @@ internal IEnumerable> ComposeContentTypeChanges(params { // find all content types impacted by the changes, // - content type alias changed - // - content type property removed, or alias changed - // - content type composition removed (not testing if composition had properties...) + // - content type property removed, added, or alias changed + // - content type composition removed or added (not testing if composition had properties...) // - content type variation changed // - property type variation changed // - // because these are the changes that would impact the raw content data + // because these are the changes that alter the set of property types a content type exposes, + // and so the set exposed by every content type that derives from it // note // this is meant to run *after* uow.Commit() so must use WasPropertyDirty() everywhere @@ -357,10 +358,14 @@ internal IEnumerable> ComposeContentTypeChanges(params var changes = new List>(); + // Shared by every content type in the batch, so a deriving type reached from more than one of them is + // the same instance each time, and AddChange merges its changes into a single entry. + ILookup? directReferencingTypes = null; + // Track which types genuinely need a raw cmsContentNu rebuild vs. which only had a property removed. // A type can appear via more than one path (e.g. a batch save touching a composition, where the same - // type is both saved directly and returned by GetComposedOf as a different instance), so we key these - // by Id — not entity reference — and resolve the RawDataUnaffected flag once at the end: it is only + // type is both saved directly and returned by the composition traversal as a different instance), so we + // key these by Id — not entity reference — and resolve the RawDataUnaffected flag once at the end: it is only // safe when *nothing* required a rebuild for that Id. var rebuildRequiredIds = new HashSet(); var rawDataUnaffectedCandidateIds = new HashSet(); @@ -416,31 +421,34 @@ internal IEnumerable> ComposeContentTypeChanges(params // does. See the rawDataAffected calculation. var hasCompositionChanged = dirty.WasPropertyDirty("ContentTypeComposition"); + // added properties? + var hasAnyPropertyBeenAdded = contentType.PropertyTypes.Any(propertyType => propertyType.WasPropertyDirty("Id")); + // main impact on properties? var hasPropertyMainImpact = hasContentTypeVariationChanged || hasAnyPropertyVariationChanged || hasAnyCompositionBeenRemoved || hasAnyPropertyBeenRemoved || hasAnyPropertyChangedAlias || hasCompositionChanged; + // The raw cmsContentNu blob is keyed by property alias, so a structural change only requires a + // rebuild when it re-keys existing stored values or lets a stale value resolve to a different + // property. It does NOT when the only structural change is: + // - a property removal - the orphaned value simply stops resolving and is never read again, or + // - a composition being added - its new aliases have no stored value yet. + // In those cases clearing the converted content cache is enough (the content type cache is + // refreshed regardless). An alias or variation change, a composition removal, or a property + // removal combined with a composition change (which can reintroduce the removed alias behind a + // different property type) all re-key or revive stored values and therefore need a rebuild. + var rawDataAffected = + hasAliasChanged || + hasAnyPropertyChangedAlias || + hasContentTypeVariationChanged || + hasAnyPropertyVariationChanged || + hasAnyCompositionBeenRemoved || + (hasAnyPropertyBeenRemoved && hasCompositionChanged); + var rawDataUnaffected = rawDataAffected is false; + if (hasAliasChanged || hasPropertyMainImpact) { - // The raw cmsContentNu blob is keyed by property alias, so a structural change only requires a - // rebuild when it re-keys existing stored values or lets a stale value resolve to a different - // property. It does NOT when the only structural change is: - // - a property removal - the orphaned value simply stops resolving and is never read again, or - // - a composition being added - its new aliases have no stored value yet. - // In those cases clearing the converted content cache is enough (the content type cache is - // refreshed regardless). An alias or variation change, a composition removal, or a property - // removal combined with a composition change (which can reintroduce the removed alias behind a - // different property type) all re-key or revive stored values and therefore need a rebuild. - var rawDataAffected = - hasAliasChanged || - hasAnyPropertyChangedAlias || - hasContentTypeVariationChanged || - hasAnyPropertyVariationChanged || - hasAnyCompositionBeenRemoved || - (hasAnyPropertyBeenRemoved && hasCompositionChanged); - var rawDataUnaffected = rawDataAffected is false; - // add that one, as a main change AddChange(changes, contentType, ContentTypeChangeTypes.RefreshMain); (rawDataUnaffected ? rawDataUnaffectedCandidateIds : rebuildRequiredIds).Add(contentType.Id); @@ -451,22 +459,39 @@ internal IEnumerable> ComposeContentTypeChanges(params { AddChange(changes, contentType, ContentTypeChangeTypes.VariationChanged); } + } + else + { + // add that one, as an other change + AddChange(changes, contentType, ContentTypeChangeTypes.RefreshOther); + } - if (hasPropertyMainImpact) + // A content type that derives from this one - through composition or inheritance, at any depth - + // resolves its published content type from this one's alias and property types, so any change to + // either has to refresh the whole closure beneath it. Left stale, a deriving type keeps projecting + // content through a property set the content type no longer has, and keeps reporting the old alias + // from its composition aliases (which IPublishedContent.IsComposedOf reads). + if (hasPropertyMainImpact || hasAnyPropertyBeenAdded || hasAliasChanged) + { + directReferencingTypes ??= GetDirectReferencingTypes(); + foreach (TItem c in GetComposedOfTransitive(contentType.Id, directReferencingTypes)) { - foreach (TItem c in GetComposedOf(contentType.Id)) + if (hasPropertyMainImpact) { - // Composing types inherit the same property change, so they share its rebuild requirement. + // Deriving types inherit the same property change, so they share its rebuild requirement. AddChange(changes, c, ContentTypeChangeTypes.RefreshMain); (rawDataUnaffected ? rawDataUnaffectedCandidateIds : rebuildRequiredIds).Add(c.Id); } + else + { + // Neither a property addition nor a content type alias change re-keys anything the + // deriving types have stored - the added alias has no value yet, and the stored blob is + // keyed by property alias, not content type alias. They only need their content type and + // converted content caches cleared, not a rebuild. + AddChange(changes, c, ContentTypeChangeTypes.RefreshOther); + } } } - else - { - // add that one, as an other change - AddChange(changes, contentType, ContentTypeChangeTypes.RefreshOther); - } } // Flag the raw data as unaffected only for types that were never independently marked as needing a @@ -705,6 +730,63 @@ public IEnumerable GetComposedOf(int id) return GetComposedOf(id, allContentTypes); } + /// + /// Builds a lookup from each content type id to the content types that directly reference it as a composition + /// (or as the content type they inherit from). + /// + /// The lookup of directly referencing content types, keyed by referenced content type id. + /// + /// Every call takes a fresh snapshot of all content types, and the full dataset cache policy deep clones each + /// of them, so build this once per unit of work and share it. + /// + private ILookup GetDirectReferencingTypes() => + GetAll() + .SelectMany( + contentType => contentType.ContentTypeComposition, + (contentType, referenced) => (ReferencedId: referenced.Id, ContentType: contentType)) + .ToLookup(x => x.ReferencedId, x => x.ContentType); + + /// + /// Gets every content type whose effective property set derives from the specified content type, directly + /// or indirectly. + /// + /// The identifier of the content type. + /// + /// The content types that directly reference each content type, as built by + /// . + /// + /// The content types deriving from the specified content type. + /// + /// Inheritance is stored as composition, so a single traversal of the composition graph covers both axes. + /// It has to be transitive because a content type resolves both its property types and its composition + /// aliases recursively through its compositions (see + /// and + /// ), so a change to one content type is a change + /// to everything deriving from it, not just to its direct consumers. + /// + private static TItem[] GetComposedOfTransitive(int id, ILookup directReferencingTypes) + { + var composedOf = new Dictionary(); + var remaining = new Stack(); + remaining.Push(id); + + while (remaining.Count > 0) + { + foreach (TItem contentType in directReferencingTypes[remaining.Pop()]) + { + // TryAdd doubles as the guard against cycles in the composition graph + if (composedOf.TryAdd(contentType.Id, contentType) is false) + { + continue; + } + + remaining.Push(contentType.Id); + } + } + + return [.. composedOf.Values]; + } + /// public int Count() { diff --git a/tests/Umbraco.Tests.Integration/Umbraco.Core/Cache/PublishedContentTypeCacheTests.cs b/tests/Umbraco.Tests.Integration/Umbraco.Core/Cache/PublishedContentTypeCacheTests.cs index da4671ab7a6b..2b4550d2cf51 100644 --- a/tests/Umbraco.Tests.Integration/Umbraco.Core/Cache/PublishedContentTypeCacheTests.cs +++ b/tests/Umbraco.Tests.Integration/Umbraco.Core/Cache/PublishedContentTypeCacheTests.cs @@ -194,6 +194,95 @@ public async Task Published_Child_Type_Reflects_Composition_Added_To_Inherited_P "child published content type should pick up the property composed onto its inherited-from parent"); } + [Test] + public async Task Published_Composing_Type_Reflects_Property_Added_To_Composition_After_Caching() + { + // A composition, applied to a composing content type. + var composition = (await ContentTypeEditingService.CreateAsync( + ContentTypeEditingBuilder.CreateSimpleContentType("composition", "Composition"), + Constants.Security.SuperUserKey)).Result!; + + var composingModel = ContentTypeEditingBuilder.CreateBasicContentType("composing", "Composing"); + composingModel.Compositions = [new Composition { CompositionType = CompositionType.Composition, Key = composition.Key }]; + var composing = (await ContentTypeEditingService.CreateAsync(composingModel, Constants.Security.SuperUserKey)).Result!; + + // Prime the published content type cache for the composing type; it does not expose "subtitle" yet. + var before = PublishedContentTypeCache.Get(PublishedItemType.Content, composing.Key); + Assert.IsFalse(before.PropertyTypes.Any(p => p.Alias == "subtitle"), "precondition: composing type should not yet expose 'subtitle'"); + + // Add a "subtitle" property to the composition. + await AddPropertyAndSaveAsync(composition, "subtitle"); + + // Adding the property must invalidate the cached published content type of the composing type, so it + // now exposes the property it gains through the composition. + var after = PublishedContentTypeCache.Get(PublishedItemType.Content, composing.Key); + Assert.IsTrue( + after.PropertyTypes.Any(p => p.Alias == "subtitle"), + "composing published content type should pick up the property added to its composition"); + } + + [Test] + public async Task Published_Descendant_Type_Reflects_Property_Added_Further_Up_The_Inheritance_Chain_After_Caching() + { + // Root <- Middle <- Leaf, each inheriting from the one before. + var root = (await ContentTypeEditingService.CreateAsync( + ContentTypeEditingBuilder.CreateSimpleContentType("root", "Root"), + Constants.Security.SuperUserKey)).Result!; + + var middleModel = ContentTypeEditingBuilder.CreateBasicContentType("middle", "Middle"); + middleModel.Compositions = [new Composition { CompositionType = CompositionType.Inheritance, Key = root.Key }]; + var middle = (await ContentTypeEditingService.CreateAsync(middleModel, Constants.Security.SuperUserKey)).Result!; + + var leafModel = ContentTypeEditingBuilder.CreateBasicContentType("leaf", "Leaf"); + leafModel.Compositions = [new Composition { CompositionType = CompositionType.Inheritance, Key = middle.Key }]; + var leaf = (await ContentTypeEditingService.CreateAsync(leafModel, Constants.Security.SuperUserKey)).Result!; + + // Prime the published content type cache for the leaf; it does not expose "subtitle" yet. + var before = PublishedContentTypeCache.Get(PublishedItemType.Content, leaf.Key); + Assert.IsFalse(before.PropertyTypes.Any(p => p.Alias == "subtitle"), "precondition: leaf should not yet expose 'subtitle'"); + + // Add a "subtitle" property two levels up. + await AddPropertyAndSaveAsync(root, "subtitle"); + + // The refresh has to reach the whole closure of deriving types, not just the direct one. + var after = PublishedContentTypeCache.Get(PublishedItemType.Content, leaf.Key); + Assert.IsTrue( + after.PropertyTypes.Any(p => p.Alias == "subtitle"), + "leaf published content type should pick up the property added to the root of its inheritance chain"); + } + + [Test] + public async Task Published_Composing_Type_Reflects_Alias_Changed_On_Composition_After_Caching() + { + // A composition, applied to a composing content type. + var composition = (await ContentTypeEditingService.CreateAsync( + ContentTypeEditingBuilder.CreateSimpleContentType("composition", "Composition"), + Constants.Security.SuperUserKey)).Result!; + + var composingModel = ContentTypeEditingBuilder.CreateBasicContentType("composing", "Composing"); + composingModel.Compositions = [new Composition { CompositionType = CompositionType.Composition, Key = composition.Key }]; + var composing = (await ContentTypeEditingService.CreateAsync(composingModel, Constants.Security.SuperUserKey)).Result!; + + // Prime the published content type cache for the composing type; it reports the composition's current alias. + var before = PublishedContentTypeCache.Get(PublishedItemType.Content, composing.Key); + Assert.IsTrue(before.CompositionAliases.Contains("composition"), "precondition: composing type should report the original composition alias"); + + // Rename the composition. + var updateModel = ContentTypeUpdateHelper.CreateContentTypeUpdateModel(composition); + updateModel.Alias = "renamedComposition"; + var result = await ContentTypeEditingService.UpdateAsync(composition, updateModel, Constants.Security.SuperUserKey); + Assert.IsTrue(result.Success, result.Status.ToString()); + + // A published content type's composition aliases are resolved recursively from its compositions, so the + // composing type has to be refreshed for IPublishedContent.IsComposedOf to report the new alias. + var after = PublishedContentTypeCache.Get(PublishedItemType.Content, composing.Key); + Assert.Multiple(() => + { + Assert.IsTrue(after.CompositionAliases.Contains("renamedComposition"), "composing published content type should report the new composition alias"); + Assert.IsFalse(after.CompositionAliases.Contains("composition"), "composing published content type should no longer report the old composition alias"); + }); + } + private async Task CreateElementTypeAsync(string alias) { ContentTypeCreateModel createModel = ContentTypeEditingBuilder.CreateElementType(alias, alias); diff --git a/tests/Umbraco.Tests.Integration/Umbraco.Core/Cache/ReloadPublishedCacheTests.cs b/tests/Umbraco.Tests.Integration/Umbraco.Core/Cache/ReloadPublishedCacheTests.cs new file mode 100644 index 000000000000..661ffa978cf5 --- /dev/null +++ b/tests/Umbraco.Tests.Integration/Umbraco.Core/Cache/ReloadPublishedCacheTests.cs @@ -0,0 +1,49 @@ +using NUnit.Framework; +using Umbraco.Cms.Core.Cache; +using Umbraco.Cms.Core.DependencyInjection; +using Umbraco.Cms.Core.Models.PublishedContent; +using Umbraco.Cms.Core.PublishedCache; +using Umbraco.Cms.Core.Sync; +using Umbraco.Cms.Tests.Common.Testing; +using Umbraco.Cms.Tests.Integration.Testing; +using Umbraco.Cms.Tests.Integration.Umbraco.Infrastructure.Services; +using Umbraco.Extensions; + +namespace Umbraco.Cms.Tests.Integration.Umbraco.Core.Cache; + +[TestFixture] +[UmbracoTest(Database = UmbracoTestOptions.Database.NewSchemaPerTest)] +internal sealed class ReloadPublishedCacheTests : UmbracoIntegrationTestWithContentEditing +{ + private IPublishedContentTypeCache PublishedContentTypeCache => GetRequiredService(); + + private DistributedCache DistributedCache => GetRequiredService(); + + protected override void CustomTestSetup(IUmbracoBuilder builder) + { + builder.AddUmbracoHybridCache(); + + // The harness registers a no-op server messenger, which would swallow the refresh and let this test + // pass without the cache refresher ever running. + builder.Services.AddUnique(); + } + + [Test] + public void Reloading_The_Published_Cache_Clears_The_Published_Content_Type_Cache() + { + IPublishedContentType primed = PublishedContentTypeCache.Get(PublishedItemType.Content, ContentType.Key); + Assert.IsNotNull(primed); + + // Establish that a cache hit really does hand back the same instance, so the assertion after the reload + // is testing the clear rather than an implementation that happens to build a new instance every time. + Assert.AreSame(primed, PublishedContentTypeCache.Get(PublishedItemType.Content, ContentType.Key), "precondition: a cache hit should re-serve the same instance"); + + // This is what the "Reload Memory Cache" backoffice action triggers. Reloading the published caches from + // the database cache is only meaningful if the content types the content is projected through are + // reloaded too, so the cached published content types have to go as well. + DistributedCache.RefreshAllPublishedSnapshot(); + + IPublishedContentType after = PublishedContentTypeCache.Get(PublishedItemType.Content, ContentType.Key); + Assert.AreNotSame(primed, after, "the published content type should have been rebuilt, not re-served from the cache"); + } +} diff --git a/tests/Umbraco.Tests.Integration/Umbraco.Core/Services/ContentTypeEditingServiceTests.Update.cs b/tests/Umbraco.Tests.Integration/Umbraco.Core/Services/ContentTypeEditingServiceTests.Update.cs index 9908b8398ada..19d2cffda88c 100644 --- a/tests/Umbraco.Tests.Integration/Umbraco.Core/Services/ContentTypeEditingServiceTests.Update.cs +++ b/tests/Umbraco.Tests.Integration/Umbraco.Core/Services/ContentTypeEditingServiceTests.Update.cs @@ -862,6 +862,101 @@ public async Task Can_Reapply_Compositions() AssertContentTypeRefreshPayload(refreshedPayloads, contentType.Id, ContentTypeChangeTypes.RefreshOther); } + [Test] + public async Task Adding_A_Property_Refreshes_The_Content_Types_Composed_Of_It() + { + var compositionContentType = (await ContentTypeEditingService.CreateAsync( + ContentTypeCreateModel("Composition", "composition"), + Constants.Security.SuperUserKey)).Result!; + + var createModel = ContentTypeCreateModel("Test", "test"); + createModel.Compositions = new[] + { + new Composition { Key = compositionContentType.Key, CompositionType = CompositionType.Composition }, + }; + var contentType = (await ContentTypeEditingService.CreateAsync(createModel, Constants.Security.SuperUserKey)).Result!; + + ContentTypeCacheRefresher.JsonPayload[]? refreshedPayloads = null; + ContentTypeCacheRefreshedNotificationHandler.ContentTypeCacheRefreshed = payloads + => refreshedPayloads = payloads; + + var updateModel = ContentTypeUpdateModel("Composition", "composition"); + updateModel.Properties = new[] { ContentTypePropertyTypeModel("Test Property", "testProperty") }; + + var result = await ContentTypeEditingService.UpdateAsync(compositionContentType, updateModel, Constants.Security.SuperUserKey); + Assert.IsTrue(result.Success); + + // The composing content type now exposes the added property, so it has to be refreshed alongside the + // content type the property was added to. The new alias has no stored value, so neither needs a rebuild. + Assert.IsNotNull(refreshedPayloads); + Assert.Multiple(() => + { + Assert.AreEqual(2, refreshedPayloads!.Length); + AssertContentTypeRefreshPayloadFor(refreshedPayloads, compositionContentType.Id, ContentTypeChangeTypes.RefreshOther); + AssertContentTypeRefreshPayloadFor(refreshedPayloads, contentType.Id, ContentTypeChangeTypes.RefreshOther); + Assert.IsFalse(refreshedPayloads.Any(x => x.ChangeTypes.RequiresRawDataRebuild()), "no payload should require a raw data rebuild"); + }); + } + + [Test] + public async Task Changing_Property_Variation_Rebuilds_Every_Content_Type_Deriving_From_It() + { + var (root, middle, leaf) = await CreateInheritanceChainAsync(variesByCulture: true); + + ContentTypeCacheRefresher.JsonPayload[]? refreshedPayloads = null; + ContentTypeCacheRefreshedNotificationHandler.ContentTypeCacheRefreshed = payloads + => refreshedPayloads = payloads; + + var container = ContentTypePropertyContainerModel(key: root.PropertyGroups.Single().Key); + var propertyTypeModel = ContentTypePropertyTypeModel("rootProperty", "rootProperty", containerKey: container.Key); + propertyTypeModel.VariesByCulture = true; + var updateModel = ContentTypeUpdateModel("Root", alias: root.Alias, propertyTypes: [propertyTypeModel], containers: [container]); + updateModel.VariesByCulture = true; + + var result = await ContentTypeEditingService.UpdateAsync(root, updateModel, Constants.Security.SuperUserKey); + Assert.IsTrue(result.Success, result.Status.ToString()); + + // The stored values change shape on every type that inherits the property, at any depth. + Assert.IsNotNull(refreshedPayloads); + Assert.Multiple(() => + { + Assert.AreEqual(3, refreshedPayloads!.Length); + AssertContentTypeRefreshPayloadFor(refreshedPayloads, root.Id, ContentTypeChangeTypes.RefreshMain); + AssertContentTypeRefreshPayloadFor(refreshedPayloads, middle.Id, ContentTypeChangeTypes.RefreshMain); + AssertContentTypeRefreshPayloadFor(refreshedPayloads, leaf.Id, ContentTypeChangeTypes.RefreshMain); + }); + } + + [Test] + public async Task Removing_A_Property_Refreshes_Every_Content_Type_Deriving_From_It_Without_A_Rebuild() + { + var (root, middle, leaf) = await CreateInheritanceChainAsync(); + + ContentTypeCacheRefresher.JsonPayload[]? refreshedPayloads = null; + ContentTypeCacheRefreshedNotificationHandler.ContentTypeCacheRefreshed = payloads + => refreshedPayloads = payloads; + + var updateModel = ContentTypeUpdateModel( + "Root", + alias: root.Alias, + propertyTypes: [], + containers: [ContentTypePropertyContainerModel(key: root.PropertyGroups.Single().Key)]); + + var result = await ContentTypeEditingService.UpdateAsync(root, updateModel, Constants.Security.SuperUserKey); + Assert.IsTrue(result.Success, result.Status.ToString()); + + // Every type that inherited the property loses it, at any depth, but the orphaned stored value is never + // read again, so none of them needs a rebuild. + Assert.IsNotNull(refreshedPayloads); + Assert.Multiple(() => + { + Assert.AreEqual(3, refreshedPayloads!.Length); + AssertContentTypeRefreshPayloadFor(refreshedPayloads, root.Id, ContentTypeChangeTypes.RefreshMain | ContentTypeChangeTypes.RawDataUnaffected); + AssertContentTypeRefreshPayloadFor(refreshedPayloads, middle.Id, ContentTypeChangeTypes.RefreshMain | ContentTypeChangeTypes.RawDataUnaffected); + AssertContentTypeRefreshPayloadFor(refreshedPayloads, leaf.Id, ContentTypeChangeTypes.RefreshMain | ContentTypeChangeTypes.RawDataUnaffected); + }); + } + [Test] public async Task Can_Remove_Compositions() { @@ -1521,13 +1616,15 @@ private static void AssertContentTypeRefreshPayload(ContentTypeCacheRefresher.Js { Assert.IsNotNull(refreshedPayloads); Assert.AreEqual(1, refreshedPayloads.Length); - Assert.Multiple(() => - { - var payload = refreshedPayloads.First(); - Assert.AreEqual(expectedContentTypeId, payload.Id); - Assert.AreEqual(expectedChangeTypes, payload.ChangeTypes); - Assert.AreEqual(nameof(IContentType), payload.ItemType); - }); + Assert.Multiple(() => AssertContentTypeRefreshPayloadFor(refreshedPayloads, expectedContentTypeId, expectedChangeTypes)); + } + + private static void AssertContentTypeRefreshPayloadFor(ContentTypeCacheRefresher.JsonPayload[] refreshedPayloads, int expectedContentTypeId, ContentTypeChangeTypes expectedChangeTypes) + { + ContentTypeCacheRefresher.JsonPayload? payload = refreshedPayloads.SingleOrDefault(x => x.Id == expectedContentTypeId); + Assert.IsNotNull(payload, $"expected a single payload for content type {expectedContentTypeId}"); + Assert.AreEqual(expectedChangeTypes, payload!.ChangeTypes); + Assert.AreEqual(nameof(IContentType), payload.ItemType); } [Test] @@ -1745,6 +1842,23 @@ private ContentTypeCreateModel ChildModelInheriting(string name, Guid parentKey, compositions: [new Composition { CompositionType = CompositionType.Inheritance, Key = parentKey }]); } + private async Task<(IContentType Root, IContentType Middle, IContentType Leaf)> CreateInheritanceChainAsync(bool variesByCulture = false) + { + var rootModel = CompositionModelWithProperty("Root", "rootProperty"); + rootModel.VariesByCulture = variesByCulture; + var root = (await ContentTypeEditingService.CreateAsync(rootModel, Constants.Security.SuperUserKey)).Result!; + + var middleModel = ChildModelInheriting("Middle", root.Key); + middleModel.VariesByCulture = variesByCulture; + var middle = (await ContentTypeEditingService.CreateAsync(middleModel, Constants.Security.SuperUserKey)).Result!; + + var leafModel = ChildModelInheriting("Leaf", middle.Key); + leafModel.VariesByCulture = variesByCulture; + var leaf = (await ContentTypeEditingService.CreateAsync(leafModel, Constants.Security.SuperUserKey)).Result!; + + return (root, middle, leaf); + } + private ContentTypeCreateModel CompositionModelWithProperty(string name, string propertyAlias) { var container = ContentTypePropertyContainerModel(); diff --git a/tests/Umbraco.Tests.Integration/Umbraco.PublishedCache.HybridCache/DocumentHybridCacheDocumentTypeTests.cs b/tests/Umbraco.Tests.Integration/Umbraco.PublishedCache.HybridCache/DocumentHybridCacheDocumentTypeTests.cs index da53df780757..48881b5464e8 100644 --- a/tests/Umbraco.Tests.Integration/Umbraco.PublishedCache.HybridCache/DocumentHybridCacheDocumentTypeTests.cs +++ b/tests/Umbraco.Tests.Integration/Umbraco.PublishedCache.HybridCache/DocumentHybridCacheDocumentTypeTests.cs @@ -157,6 +157,81 @@ public async Task Batch_Save_Does_Not_Flag_A_Type_That_Independently_Requires_A_ }); } + /// + /// Adding a property to a composition changes the property set of every content type composed of it, so + /// their published content has to expose the new property too. The added alias has no stored value yet, + /// so this must not rebuild the stored database cache. + /// + [Test] + public async Task Adding_Property_To_A_Composition_Exposes_It_On_Composed_Content() + { + // Arrange - compose the Textpage's content type, then read the published content so both its published + // content type and its converted instance are cached against the property set as it stands now. + var composition = await CreateContentType("compositionType", "compProp"); + ContentType.AddContentType(composition); + await ContentTypeService.UpdateAsync(ContentType, Constants.Security.SuperUserKey); + + var before = await PublishedContentHybridCache.GetByIdAsync(TextpageId, true); + Assert.That(before!.HasProperty("addedProp"), Is.False, "precondition: the property does not exist yet"); + var blobBefore = ReadDraftBlobSignature(TextpageId); + + // Act - add a property to the composition, and only to the composition. + composition.AddPropertyType( + new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext, "addedProp") + { + Name = "addedProp", + DataTypeId = Constants.DataTypes.Textbox, + }, + "content", + "Content"); + await ContentTypeService.UpdateAsync(composition, Constants.Security.SuperUserKey); + + // Assert - the composing type's published content exposes the property it gains through the composition. + // Left stale, it keeps serving an instance built against the old property set, and Value() returns null + // no matter how the property is populated and published. + var after = await PublishedContentHybridCache.GetByIdAsync(TextpageId, true); + Assert.That(after!.HasProperty("addedProp"), Is.True, "Templates must be able to read the property added to the composition."); + + // Assert - the stored cmsContentNu blob was NOT rebuilt; the added alias has no stored value to re-key. + Assert.That(ReadDraftBlobSignature(TextpageId), Is.EqualTo(blobBefore), "Adding a property must not rebuild the stored blob."); + } + + /// + /// A content type deriving from several content types saved in the same batch is one content type, so it + /// must surface as a single change however many of them it is reached from. + /// + [Test] + public async Task Batch_Save_Reports_A_Single_Change_For_A_Type_Deriving_From_Several_Saved_Types() + { + var compositionA = await CreateContentType("compositionA", "compPropA"); + var compositionB = await CreateContentType("compositionB", "compPropB"); + var composing = await CreateContentType("composingType", "ownProp", compositionA); + composing.AddContentType(compositionB); + await ContentTypeService.UpdateAsync(composing, Constants.Security.SuperUserKey); + + _capturedContentTypeChanges.Clear(); + + // Act - add a property to both compositions, saved together as a single batch. + AddTextBoxProperty(compositionA, "addedPropA"); + AddTextBoxProperty(compositionB, "addedPropB"); +#pragma warning disable CS0618 // Type or member is obsolete + ContentTypeService.Save([compositionA, compositionB]); +#pragma warning restore CS0618 // Type or member is obsolete + + // Assert + Assert.That(ChangeTypesFor(composing.Id), Has.Count.EqualTo(1)); + } + + private void AddTextBoxProperty(IContentType contentType, string propertyAlias) => + contentType.AddPropertyType( + new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext, propertyAlias) + { + Name = propertyAlias, + DataTypeId = Constants.DataTypes.Textbox, + }, + "content", + "Content"); + private IReadOnlyList ChangeTypesFor(int contentTypeId) => _capturedContentTypeChanges.Where(c => c.Item.Id == contentTypeId).Select(c => c.ChangeTypes).ToList(); diff --git a/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Cache/ContentCacheRefresherIdKeyMapTests.cs b/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Cache/ContentCacheRefresherIdKeyMapTests.cs index 5cb16592858d..ca19d60c3659 100644 --- a/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Cache/ContentCacheRefresherIdKeyMapTests.cs +++ b/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Cache/ContentCacheRefresherIdKeyMapTests.cs @@ -68,6 +68,7 @@ private ContentCacheRefresher CreateRefresher() Mock.Of(), Mock.Of(), Mock.Of(), - Mock.Of(x => x.ElementsCache == Mock.Of())); + Mock.Of(x => x.ElementsCache == Mock.Of()), + Mock.Of()); } } From e09b43d45e9d4c6f270d923dbd1abc1eebf9740f Mon Sep 17 00:00:00 2001 From: Jacob Overgaard <752371+iOvergaard@users.noreply.github.com> Date: Fri, 9 Oct 2026 14:24:41 +0200 Subject: [PATCH 2/4] Password reset: Report an unconfigured application URL before the user lookup and always apply the minimum response time (#24152) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(api): report an unconfigured application URL before the password reset user lookup ApplicationUrlNotConfigured was only produced once the user had been found, so the reset endpoint answered a registered email differently from an unknown one on sites where the application URL could not be resolved. Add IForgotPasswordUriProvider.CanCreateForgotPasswordUriAsync for failures that don't depend on the user, and check it before the lookup. The default implementation succeeds, so existing providers are unaffected. Co-Authored-By: Claude Opus 5.5 * fix(api): always apply the minimum response time on password reset endpoints The filter checked TimeSpan.Microseconds, which is only the 0-999 µs component of the remaining wait, so the delay was skipped whenever that component happened to be zero. Compare the whole TimeSpan instead, and measure with TimeProvider so the behaviour can be tested deterministically. Co-Authored-By: Claude Opus 5.5 * Added docs for EnsureMinimumResponseTimeFilter. --------- Co-authored-by: Claude Opus 5.5 Co-authored-by: Andy Butland --- .../Security/ResetPasswordController.cs | 3 +- .../EnsureMinimumResponseTimeFilter.cs | 40 ++++++++++--- .../Security/ForgotPasswordUriProvider.cs | 6 ++ .../Security/IForgotPasswordUriProvider.cs | 16 ++++++ src/Umbraco.Core/Services/UserService.cs | 8 ++- .../UserServiceCrudTests.ResetPassword.cs | 16 ++++++ .../Services/UserServiceCrudTests.cs | 15 +++++ .../EnsureMinimumResponseTimeFilterTests.cs | 57 +++++++++++++++++++ .../Security/UriProviderTests.cs | 31 ++++++++++ 9 files changed, 180 insertions(+), 12 deletions(-) create mode 100644 tests/Umbraco.Tests.UnitTests/Umbraco.Cms.Api.Management/Filters/EnsureMinimumResponseTimeFilterTests.cs diff --git a/src/Umbraco.Cms.Api.Management/Controllers/Security/ResetPasswordController.cs b/src/Umbraco.Cms.Api.Management/Controllers/Security/ResetPasswordController.cs index ccb1eccb8639..a62901e705ba 100644 --- a/src/Umbraco.Cms.Api.Management/Controllers/Security/ResetPasswordController.cs +++ b/src/Umbraco.Cms.Api.Management/Controllers/Security/ResetPasswordController.cs @@ -49,8 +49,7 @@ public async Task RequestPasswordReset(CancellationToken cancella // If this feature is switched off in configuration, the UI will be amended to not make the request to reset password available. // So this is just a server-side secondary check. - // ApplicationUrlNotConfigured is also surfaced since it is a server-wide configuration issue, not user-specific. - // PasswordResetUnavailable is surfaced as it's determined before the user lookup, so it's the same for every email. + // ApplicationUrlNotConfigured and PasswordResetUnavailable are surfaced as they're determined before the user lookup, so they're the same for every email. // Regardless of other status values, it will just return Ok, so you can't use this endpoint to determine whether the email exists in the system. return result.Result switch { diff --git a/src/Umbraco.Cms.Api.Management/Filters/EnsureMinimumResponseTimeFilter.cs b/src/Umbraco.Cms.Api.Management/Filters/EnsureMinimumResponseTimeFilter.cs index 19e6237ca970..6a2c40d05301 100644 --- a/src/Umbraco.Cms.Api.Management/Filters/EnsureMinimumResponseTimeFilter.cs +++ b/src/Umbraco.Cms.Api.Management/Filters/EnsureMinimumResponseTimeFilter.cs @@ -1,13 +1,38 @@ -using System.Diagnostics; using Microsoft.AspNetCore.Mvc.Filters; namespace Umbraco.Cms.Api.Management.Filters; +/// +/// An action filter that delays the response until a minimum amount of time has elapsed since the action started executing. +/// +/// +/// Giving every response the same minimum duration prevents an endpoint's timing from revealing which path it took, +/// for example whether a submitted email address belongs to a user. +/// internal abstract class EnsureMinimumResponseTimeFilter : IAsyncActionFilter { private readonly TimeSpan _minimumResponseTime; + private readonly TimeProvider _timeProvider; - protected EnsureMinimumResponseTimeFilter(TimeSpan minimumResponseTime) => _minimumResponseTime = minimumResponseTime; + /// + /// Initializes a new instance of the class using the system clock. + /// + /// The minimum time a response takes, measured from when the action starts executing. + protected EnsureMinimumResponseTimeFilter(TimeSpan minimumResponseTime) + : this(minimumResponseTime, TimeProvider.System) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The minimum time a response takes, measured from when the action starts executing. + /// The time provider used to measure the elapsed time and to delay the response. + protected EnsureMinimumResponseTimeFilter(TimeSpan minimumResponseTime, TimeProvider timeProvider) + { + _minimumResponseTime = minimumResponseTime; + _timeProvider = timeProvider; + } /// /// Ensures that the action execution takes at least a minimum amount of time by delaying the response if necessary. @@ -17,17 +42,14 @@ internal abstract class EnsureMinimumResponseTimeFilter : IAsyncActionFilter /// A task that represents the asynchronous operation. public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) { - var stopwatch = new Stopwatch(); - - stopwatch.Start(); + var startTimestamp = _timeProvider.GetTimestamp(); await next(); - stopwatch.Stop(); - TimeSpan forceWait = _minimumResponseTime.Subtract(stopwatch.Elapsed); + TimeSpan forceWait = _minimumResponseTime - _timeProvider.GetElapsedTime(startTimestamp); - if (forceWait.Microseconds > 0) + if (forceWait > TimeSpan.Zero) { - await Task.Delay(forceWait).ConfigureAwait(false); + await Task.Delay(forceWait, _timeProvider).ConfigureAwait(false); } } } diff --git a/src/Umbraco.Cms.Api.Management/Security/ForgotPasswordUriProvider.cs b/src/Umbraco.Cms.Api.Management/Security/ForgotPasswordUriProvider.cs index 7d71500a2ce6..794e9c82761a 100644 --- a/src/Umbraco.Cms.Api.Management/Security/ForgotPasswordUriProvider.cs +++ b/src/Umbraco.Cms.Api.Management/Security/ForgotPasswordUriProvider.cs @@ -67,4 +67,10 @@ public async Task> CreateForgotPasswordUriAsyn return Attempt.SucceedWithStatus(UserOperationStatus.Success, uriBuilder.Uri); } + + /// + public Task> CanCreateForgotPasswordUriAsync() + => Task.FromResult(_hostingEnvironment.ApplicationMainUrl is null + ? Attempt.Fail(UserOperationStatus.ApplicationUrlNotConfigured) + : Attempt.Succeed(UserOperationStatus.Success)); } diff --git a/src/Umbraco.Core/Security/IForgotPasswordUriProvider.cs b/src/Umbraco.Core/Security/IForgotPasswordUriProvider.cs index 87a931331c53..0a8192fe9e33 100644 --- a/src/Umbraco.Core/Security/IForgotPasswordUriProvider.cs +++ b/src/Umbraco.Core/Security/IForgotPasswordUriProvider.cs @@ -13,5 +13,21 @@ public interface IForgotPasswordUriProvider /// /// The user to create the forgot password URI for. /// An attempt containing the generated URI or an error status. + /// + /// Failures that do not depend on the user should also be reported by + /// , so they are reported the same way whether or not the email + /// belongs to a user. + /// Task> CreateForgotPasswordUriAsync(IUser user); + + /// + /// Determines whether forgot password URIs can currently be created, regardless of the user they are for. + /// + /// A successful attempt, or a failed attempt with the reason URIs cannot be created. + /// + /// This is checked before the user is looked up, so the outcome must not depend on any particular user. + /// + // TODO (V19): Remove the default implementation. + Task> CanCreateForgotPasswordUriAsync() + => Task.FromResult(Attempt.Succeed(UserOperationStatus.Success)); } diff --git a/src/Umbraco.Core/Services/UserService.cs b/src/Umbraco.Core/Services/UserService.cs index f1fdb25f3545..917f1c8a20cd 100644 --- a/src/Umbraco.Core/Services/UserService.cs +++ b/src/Umbraco.Core/Services/UserService.cs @@ -644,6 +644,13 @@ public async Task> SendResetPasswordEmailAsync(stri ICoreBackOfficeUserManager userManager = serviceScope.ServiceProvider.GetRequiredService(); IBackOfficeUserStore userStore = serviceScope.ServiceProvider.GetRequiredService(); + IForgotPasswordUriProvider uriProvider = serviceScope.ServiceProvider.GetRequiredService(); + + Attempt canCreateUriAttempt = await uriProvider.CanCreateForgotPasswordUriAsync(); + if (canCreateUriAttempt.Success is false) + { + return Attempt.Fail(canCreateUriAttempt.Result); + } IUser? user = await userStore.GetByEmailAsync(userEmail); @@ -652,7 +659,6 @@ public async Task> SendResetPasswordEmailAsync(stri return Attempt.Fail(UserOperationStatus.UserNotFound); } - IForgotPasswordUriProvider uriProvider = serviceScope.ServiceProvider.GetRequiredService(); Attempt uriAttempt = await uriProvider.CreateForgotPasswordUriAsync(user); if (uriAttempt.Success is false) { diff --git a/tests/Umbraco.Tests.Integration/Umbraco.Core/Services/UserServiceCrudTests.ResetPassword.cs b/tests/Umbraco.Tests.Integration/Umbraco.Core/Services/UserServiceCrudTests.ResetPassword.cs index 0f7c07295dff..4e4743d22604 100644 --- a/tests/Umbraco.Tests.Integration/Umbraco.Core/Services/UserServiceCrudTests.ResetPassword.cs +++ b/tests/Umbraco.Tests.Integration/Umbraco.Core/Services/UserServiceCrudTests.ResetPassword.cs @@ -29,6 +29,22 @@ public async Task Reset_Password_Unavailable_Status_Does_Not_Depend_On_Whether_U senderMock.Verify(x => x.SendForgotPassword(It.IsAny()), Times.Never); } + [TestCase(ResetPasswordUserEmail)] + [TestCase("unknown@test.com")] + public async Task Reset_Password_Link_Unavailable_Status_Does_Not_Depend_On_Whether_User_Exists(string email) + { + GetRequiredService().CanCreateStatus = UserOperationStatus.ApplicationUrlNotConfigured; + var senderMock = CreateForgotPasswordSenderMock(canSendNow: true); + var userService = CreateUserService(forgotPasswordSender: senderMock.Object); + await CreateResetPasswordUser(userService); + + var result = await userService.SendResetPasswordEmailAsync(email, CancellationToken.None); + + Assert.IsFalse(result.Success); + Assert.AreEqual(UserOperationStatus.ApplicationUrlNotConfigured, result.Result); + senderMock.Verify(x => x.SendForgotPassword(It.IsAny()), Times.Never); + } + [Test] public async Task Reset_Password_Send_Failure_Is_Returned_As_Failed_Attempt() { diff --git a/tests/Umbraco.Tests.Integration/Umbraco.Core/Services/UserServiceCrudTests.cs b/tests/Umbraco.Tests.Integration/Umbraco.Core/Services/UserServiceCrudTests.cs index 0ebef9daa561..96b8944acb5c 100644 --- a/tests/Umbraco.Tests.Integration/Umbraco.Core/Services/UserServiceCrudTests.cs +++ b/tests/Umbraco.Tests.Integration/Umbraco.Core/Services/UserServiceCrudTests.cs @@ -35,6 +35,7 @@ protected override void ConfigureTestServices(IServiceCollection services) services.RemoveAll(); services.AddScoped(); services.RemoveAll(); + services.AddSingleton(); services.AddScoped(); } @@ -49,14 +50,28 @@ public Task> CreateInviteUriAsync(IUser invite } } + private class TestForgotPasswordUriProviderState + { + public UserOperationStatus CanCreateStatus { get; set; } = UserOperationStatus.Success; + } + private class TestForgotPasswordUriProvider : IForgotPasswordUriProvider { + private readonly TestForgotPasswordUriProviderState _state; + + public TestForgotPasswordUriProvider(TestForgotPasswordUriProviderState state) => _state = state; + public Task> CreateForgotPasswordUriAsync(IUser user) { var fakePath = "https://localhost:44331/fakeForgotPasswordEndpoint"; Attempt attempt = Attempt.Succeed(UserOperationStatus.Success, new Uri(fakePath)); return Task.FromResult(attempt); } + + public Task> CanCreateForgotPasswordUriAsync() + => Task.FromResult(_state.CanCreateStatus == UserOperationStatus.Success + ? Attempt.Succeed(UserOperationStatus.Success) + : Attempt.Fail(_state.CanCreateStatus)); } private IUserService CreateUserService( diff --git a/tests/Umbraco.Tests.UnitTests/Umbraco.Cms.Api.Management/Filters/EnsureMinimumResponseTimeFilterTests.cs b/tests/Umbraco.Tests.UnitTests/Umbraco.Cms.Api.Management/Filters/EnsureMinimumResponseTimeFilterTests.cs new file mode 100644 index 000000000000..cfce34d7fbe8 --- /dev/null +++ b/tests/Umbraco.Tests.UnitTests/Umbraco.Cms.Api.Management/Filters/EnsureMinimumResponseTimeFilterTests.cs @@ -0,0 +1,57 @@ +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using Microsoft.AspNetCore.Mvc.Filters; +using Microsoft.Extensions.Time.Testing; +using NUnit.Framework; +using Umbraco.Cms.Api.Management.Filters; + +namespace Umbraco.Cms.Tests.UnitTests.Umbraco.Cms.Api.Management.Filters; + +[TestFixture] +public class EnsureMinimumResponseTimeFilterTests +{ + private static readonly TimeSpan MinimumResponseTime = TimeSpan.FromSeconds(2); + + [TestCase(500)] + [TestCase(1234.567)] + public async Task Delays_The_Response_Until_The_Minimum_Response_Time_Has_Elapsed(double actionMilliseconds) + { + var timeProvider = new FakeTimeProvider(); + var sut = new TestEnsureMinimumResponseTimeFilter(MinimumResponseTime, timeProvider); + + Task execution = sut.OnActionExecutionAsync(null!, CreateAction(timeProvider, TimeSpan.FromMilliseconds(actionMilliseconds))); + + Assert.IsFalse(execution.IsCompleted, "The response was not delayed."); + + timeProvider.Advance(MinimumResponseTime - TimeSpan.FromMilliseconds(actionMilliseconds)); + await execution.WaitAsync(TimeSpan.FromSeconds(5)); + } + + [Test] + public async Task Does_Not_Delay_The_Response_When_The_Minimum_Response_Time_Has_Already_Elapsed() + { + var timeProvider = new FakeTimeProvider(); + var sut = new TestEnsureMinimumResponseTimeFilter(MinimumResponseTime, timeProvider); + + Task execution = sut.OnActionExecutionAsync(null!, CreateAction(timeProvider, MinimumResponseTime + TimeSpan.FromMilliseconds(1))); + + Assert.IsTrue(execution.IsCompleted, "The response was delayed."); + await execution; + } + + private static ActionExecutionDelegate CreateAction(FakeTimeProvider timeProvider, TimeSpan duration) + => () => + { + timeProvider.Advance(duration); + return Task.FromResult(null!); + }; + + private sealed class TestEnsureMinimumResponseTimeFilter : EnsureMinimumResponseTimeFilter + { + public TestEnsureMinimumResponseTimeFilter(TimeSpan minimumResponseTime, TimeProvider timeProvider) + : base(minimumResponseTime, timeProvider) + { + } + } +} diff --git a/tests/Umbraco.Tests.UnitTests/Umbraco.Cms.Api.Management/Security/UriProviderTests.cs b/tests/Umbraco.Tests.UnitTests/Umbraco.Cms.Api.Management/Security/UriProviderTests.cs index c716733a8fd9..1ec81e75ffe5 100644 --- a/tests/Umbraco.Tests.UnitTests/Umbraco.Cms.Api.Management/Security/UriProviderTests.cs +++ b/tests/Umbraco.Tests.UnitTests/Umbraco.Cms.Api.Management/Security/UriProviderTests.cs @@ -73,6 +73,37 @@ public async Task ForgotPasswordUri_WithoutApplicationMainUrl_FailsWithApplicati _userManager.Verify(m => m.GeneratePasswordResetTokenAsync(It.IsAny()), Times.Never()); } + [Test] + public async Task CanCreateForgotPasswordUri_WithApplicationMainUrl_Succeeds() + { + _hostingEnvironment.Setup(h => h.ApplicationMainUrl).Returns(new Uri("https://my-site.com")); + + var sut = new ForgotPasswordUriProvider( + _userManager.Object, + _hostingEnvironment.Object, + _httpContextAccessor.Object); + + Attempt result = await sut.CanCreateForgotPasswordUriAsync(); + + Assert.IsTrue(result.Success); + } + + [Test] + public async Task CanCreateForgotPasswordUri_WithoutApplicationMainUrl_FailsWithApplicationUrlNotConfigured() + { + _hostingEnvironment.Setup(h => h.ApplicationMainUrl).Returns((Uri?)null); + + var sut = new ForgotPasswordUriProvider( + _userManager.Object, + _hostingEnvironment.Object, + _httpContextAccessor.Object); + + Attempt result = await sut.CanCreateForgotPasswordUriAsync(); + + Assert.IsFalse(result.Success); + Assert.AreEqual(UserOperationStatus.ApplicationUrlNotConfigured, result.Result); + } + [Test] public async Task InviteUri_WithApplicationMainUrl_ReturnsAbsoluteUri() { From eb1724013d481d82f254480215b1c872199a98bd Mon Sep 17 00:00:00 2001 From: Andy Butland Date: Mon, 12 Oct 2026 06:39:59 +0100 Subject: [PATCH 3/4] Dependency Tracking: Swap `CycloneDX` for `Umbraco.Internal.Sbom` in SBOM pipeline (#23422) * Update raw use of CycloneDX to swap for Umbraco's wrapping tool. * Fix path in memory file. * Explicitly restore projects omitted from the release build configuration. * Fix location of bom-login artifact. * Add isLatestTag. * Track classifier. --- CLAUDE.md | 14 +++++++ build/azure-pipelines.yml | 57 ++++++++++++++++++++-------- build/templates/dependency-track.yml | 36 +++++++++++++++++- 3 files changed, 91 insertions(+), 16 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index a0d32c998823..a7722fd5d4f4 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -392,6 +392,20 @@ public interface IMyService - `.editorconfig` - Code style rules - `.globalconfig` - Roslyn analyzer rules +### SBOM Generation & License Policy (Azure Pipelines) + +`build/azure-pipelines.yml` generates a CycloneDX SBOM per project (Backend/NuGet, Login UI, Backoffice, E2E), each in its own job in the `Dependency_Track` stage, via **`umbraco-sbom`** (the `Umbraco.Internal.Sbom` .NET 10 global tool), not plain `dotnet CycloneDX` / `@cyclonedx/cyclonedx-npm`. It adds license-policy enforcement over CycloneDX. Repo (private): https://github.com/umbraco/Umbraco.Internal.Sbom — README has the full flag/exit-code/policy reference. + +When editing those steps: + +- **Output filenames and artifacts** (`bom-dotnet.xml`, `bom-login.xml`, `bom-backoffice.xml`, `bom-e2e.xml`) are mapped to Dependency-Track projects in the stage's `build/templates/dependency-track.yml` parameters — keep them in step. +- **Usage**: `umbraco-sbom --output-file [policy flags]`. Only `--output-file` plus policy flags (`--allow-package`, `--allow-commercial`, `--allow-copyleft`, `--fail-on-unknown`, `--policy-allow-file`) exist. +- **Commercial packages** need `--allow-package`, else **exit 50**. Backend uses `nuget:SixLabors.*` (covers both `SixLabors.ImageSharp` and `.ImageSharp.Web`). +- **`isLatest`**: DT allows one latest version per project name, and projects are `Umbraco-CMS` (children `Umbraco-CMS-Backend` etc.) versioned by major. Only a stable public release of `main`'s major (read from `main`'s `version.json` at upload time) is marked latest; older-major releases upload with `false`. +- **Exit 10** = success-with-warnings (unresolved licenses; SBOM still written). Each step tolerates it: `if ($LASTEXITCODE -ne 0 -and $LASTEXITCODE -ne 10) { exit $LASTEXITCODE }; exit 0`. +- **Every BOM job** needs a `UseDotNet@2` (`useGlobalJson: true`) step before the tool install (the .NET 10 tool needs the SDK, including in the otherwise Node-only frontend jobs). +- **Backend** must restore before scanning: `umbraco-sbom` needs every project in the solution restored, including the two the solution restore skips (`Umbraco.Tests.AcceptanceTest.UmbracoProject`, `Umbraco.JsonSchema`). + ### Persistence Layer - NPoco and EF Core The repository contains BOTH (actively supported): diff --git a/build/azure-pipelines.yml b/build/azure-pipelines.yml index 8c502367da9e..8f9644c2490a 100644 --- a/build/azure-pipelines.yml +++ b/build/azure-pipelines.yml @@ -721,6 +721,8 @@ stages: uploadToDependencyTrack: $[ or(eq(stageDependencies.Build.A.outputs['build.NBGV_PublicRelease'], 'True'), eq('${{ parameters.uploadDependencyTrack }}', 'True')) ] # Determine Umbraco version based on whether it's a public release or not. If public release, use major version, else use full NuGet package version. umbracoVersion: $[ iif(eq(stageDependencies.Build.A.outputs['build.NBGV_PublicRelease'], 'True'), stageDependencies.Build.A.outputs['build.NBGV_VersionMajor'], stageDependencies.Build.A.outputs['build.NBGV_NuGetPackageVersion']) ] + # A stable public release may become the latest version; the template confirms it is a release of main's major. + isStableRelease: $[ and(eq(stageDependencies.Build.A.outputs['build.NBGV_PublicRelease'], 'True'), eq(stageDependencies.Build.A.outputs['build.NBGV_PrereleaseVersionNoLeadingHyphen'], '')) ] jobs: - job: Dotnet_BOM displayName: Generate Backend BOM @@ -736,9 +738,17 @@ stages: displayName: Use .NET SDK from global.json inputs: useGlobalJson: true - - bash: | - dotnet tool install --global CycloneDX --version 6.2.0 - dotnet-CycloneDX $(solution) --spec-version 1.5 --output $(Build.ArtifactStagingDirectory)/bom --filename bom-dotnet.xml + - powershell: | + dotnet tool install --global Umbraco.Internal.Sbom + # umbraco-sbom scans every project in the solution and requires each to be restored. + # These two are excluded from the solution build configuration, so the solution restore + # skips them; restore them explicitly to avoid a failure. + dotnet restore $(solution) + dotnet restore $(Build.SourcesDirectory)/tests/Umbraco.Tests.AcceptanceTest.UmbracoProject/Umbraco.Tests.AcceptanceTest.UmbracoProject.csproj + dotnet restore $(Build.SourcesDirectory)/tools/Umbraco.JsonSchema/Umbraco.JsonSchema.csproj + umbraco-sbom $(solution) --output-file $(Build.ArtifactStagingDirectory)/bom/bom-dotnet.xml --allow-package nuget:SixLabors.* + if ($LASTEXITCODE -ne 0 -and $LASTEXITCODE -ne 10) { exit $LASTEXITCODE } + exit 0 displayName: Generate Backend BOM - publish: $(Build.ArtifactStagingDirectory)/bom artifact: bom-backend @@ -755,11 +765,16 @@ stages: fetchDepth: 1 fetchFilter: tree:0 - template: templates/backoffice-install.yml - - bash: | - npm install --global --ignore-scripts @cyclonedx/cyclonedx-npm@6.0.1 - cyclonedx-npm -o $(Build.ArtifactStagingDirectory)/bom/bom-backoffice.xml --ignore-npm-errors --verbose + - task: UseDotNet@2 + displayName: Use .NET SDK from global.json + inputs: + useGlobalJson: true + - powershell: | + dotnet tool install --global Umbraco.Internal.Sbom + umbraco-sbom $(Build.SourcesDirectory)/src/Umbraco.Web.UI.Client --output-file $(Build.ArtifactStagingDirectory)/bom/bom-backoffice.xml + if ($LASTEXITCODE -ne 0 -and $LASTEXITCODE -ne 10) { exit $LASTEXITCODE } + exit 0 displayName: Generate Backoffice UI BOM - workingDirectory: src/Umbraco.Web.UI.Client - publish: $(Build.ArtifactStagingDirectory)/bom artifact: bom-backoffice displayName: Publish Backoffice UI BOM @@ -783,11 +798,16 @@ stages: - script: npm ci --no-fund --no-audit --ignore-scripts displayName: Run npm ci (Login) workingDirectory: src/Umbraco.Web.UI.Login - - bash: | - npm install --global --ignore-scripts @cyclonedx/cyclonedx-npm@6.0.1 - cyclonedx-npm -o $(Build.ArtifactStagingDirectory)/bom/bom-login.xml --ignore-npm-errors --verbose + - task: UseDotNet@2 + displayName: Use .NET SDK from global.json + inputs: + useGlobalJson: true + - powershell: | + dotnet tool install --global Umbraco.Internal.Sbom + umbraco-sbom $(Build.SourcesDirectory)/src/Umbraco.Web.UI.Login --output-file $(Build.ArtifactStagingDirectory)/bom/bom-login.xml + if ($LASTEXITCODE -ne 0 -and $LASTEXITCODE -ne 10) { exit $LASTEXITCODE } + exit 0 displayName: Generate Login UI BOM - workingDirectory: src/Umbraco.Web.UI.Login - publish: $(Build.ArtifactStagingDirectory)/bom artifact: bom-login displayName: Publish Login UI BOM @@ -805,11 +825,16 @@ stages: - template: templates/e2e-install.yml parameters: npm_config_cache: ${{ variables.npm_config_cache }} - - bash: | - npm install --global --ignore-scripts @cyclonedx/cyclonedx-npm@6.0.1 - cyclonedx-npm -o $(Build.ArtifactStagingDirectory)/bom/bom-e2e.xml --ignore-npm-errors --verbose + - task: UseDotNet@2 + displayName: Use .NET SDK from global.json + inputs: + useGlobalJson: true + - powershell: | + dotnet tool install --global Umbraco.Internal.Sbom + umbraco-sbom $(Build.SourcesDirectory)/tests/Umbraco.Tests.AcceptanceTest --output-file $(Build.ArtifactStagingDirectory)/bom/bom-e2e.xml + if ($LASTEXITCODE -ne 0 -and $LASTEXITCODE -ne 10) { exit $LASTEXITCODE } + exit 0 displayName: Generate E2E Tests BOM - workingDirectory: tests/Umbraco.Tests.AcceptanceTest - publish: $(Build.ArtifactStagingDirectory)/bom artifact: bom-e2e displayName: Publish E2E BOM @@ -820,6 +845,8 @@ stages: condition: and(succeeded(), eq(variables['uploadToDependencyTrack'], 'True')) projectName: "Umbraco-CMS" umbracoVersion: $(umbracoVersion) + isLatestCandidate: $(isStableRelease) + latestVersionFileUrl: "https://raw.githubusercontent.com/umbraco/Umbraco-CMS/main/version.json" projects: - name: "Backend" artifact: "bom-backend" diff --git a/build/templates/dependency-track.yml b/build/templates/dependency-track.yml index 9bc123870c68..596eef515d40 100644 --- a/build/templates/dependency-track.yml +++ b/build/templates/dependency-track.yml @@ -9,6 +9,14 @@ parameters: type: string - name: umbracoVersion type: string + # When true, the upload is marked as the project's latest version if its major matches the + # major of the version.json at latestVersionFileUrl. Dependency-Track keeps one latest version per project name. + - name: isLatestCandidate + type: string + default: 'false' + - name: latestVersionFileUrl + type: string + default: '' - name: projects type: object @@ -21,15 +29,36 @@ jobs: - checkout: none - bash: | + is_latest=false + if [ "$(echo '${{ parameters.isLatestCandidate }}' | tr '[:upper:]' '[:lower:]')" == "true" ]; then + latest_major=$(curl --fail --no-progress-meter "${{ parameters.latestVersionFileUrl }}" | jq -r '.version' | cut -d. -f1) + this_major=$(echo "${{ parameters.umbracoVersion }}" | cut -d. -f1) + if [ -z "$latest_major" ] || [ "$latest_major" == "null" ]; then + echo "##vso[task.logissue type=warning]Could not read the latest major from ${{ parameters.latestVersionFileUrl }}; not marking as latest." + elif [ "$this_major" == "$latest_major" ]; then + is_latest=true + fi + fi + echo "Marking as latest version: $is_latest" + echo "##vso[task.setvariable variable=isLatest;isOutput=true]$is_latest" + project_id=$(curl --no-progress-meter -H "X-Api-Key: $(DT_API_KEY)" "$(DT_API_URI)/api/v1/project/lookup?name=${{ parameters.projectName }}&version=${{ parameters.umbracoVersion }}" | jq -r '.uuid') if [ "$project_id" != "null" ] && [ -n "$project_id" ]; then echo "Project '${{ parameters.projectName }}' with version '${{ parameters.umbracoVersion }}' already exists (ID: $project_id)." + if [ "$is_latest" == "true" ]; then + curl --fail --no-progress-meter \ + -X PATCH "$(DT_API_URI)/api/v1/project/$project_id" \ + -H "X-Api-Key: $(DT_API_KEY)" \ + -H "Content-Type: application/json" \ + -d '{"isLatest": true}' > /dev/null + echo "Marked existing project '${{ parameters.projectName }}' version '${{ parameters.umbracoVersion }}' as latest." + fi else project_id=$(curl --no-progress-meter \ -X PUT "$(DT_API_URI)/api/v1/project" \ -H "X-Api-Key: $(DT_API_KEY)" \ -H "Content-Type: application/json" \ - -d '{"name": "${{ parameters.projectName }}", "version": "${{ parameters.umbracoVersion }}", "collectionLogic": "AGGREGATE_DIRECT_CHILDREN"}' \ + -d '{"name": "${{ parameters.projectName }}", "version": "${{ parameters.umbracoVersion }}", "collectionLogic": "AGGREGATE_DIRECT_CHILDREN", "isLatest": '"$is_latest"'}' \ | jq -r '.uuid') if [ -z "$project_id" ] || [ "$project_id" == "null" ]; then echo "Failed to create project '${{ parameters.projectName }}' version '${{ parameters.umbracoVersion }}'." @@ -37,6 +66,7 @@ jobs: fi echo "Created project '${{ parameters.projectName }}' with version '${{ parameters.umbracoVersion }}' (ID: $project_id)." fi + name: project displayName: Ensure main project exists in Dependency Track - ${{ each project in parameters.projects }}: @@ -44,6 +74,8 @@ jobs: displayName: Upload ${{ project.name }} BOM dependsOn: Create_DT_Project condition: ${{ parameters.condition }} + variables: + isLatest: $[ dependencies.Create_DT_Project.outputs['project.isLatest'] ] steps: - checkout: none @@ -56,9 +88,11 @@ jobs: dtrackURI: $(DT_API_URI) dtrackAPIKey: $(DT_API_KEY) dtrackProjAutoCreate: true + dtrackProjClassifier: APPLICATION dtrackProjName: '${{ parameters.projectName }}-${{ project.name }}' dtrackProjVersion: ${{ parameters.umbracoVersion }} dtrackParentProjName: ${{ parameters.projectName }} dtrackParentProjVersion: ${{ parameters.umbracoVersion }} + dtrackIsLatest: $(isLatest) bomFilePath: '$(Pipeline.Workspace)/${{ project.artifact }}/${{ project.bomFilePath }}' displayName: Upload ${{ project.name }} BOM to Dependency Track From ec4eec3b59af60a27ca49dbf48839deeb1824f1f Mon Sep 17 00:00:00 2001 From: Andy Butland Date: Mon, 12 Oct 2026 07:21:23 +0100 Subject: [PATCH 4/4] Replace the lazy StaticServiceProvider lookup with constructor injection in ContentCacheRefresher. --- .../Implement/ContentCacheRefresher.cs | 154 ++++++++++++++++-- .../ContentCacheRefresherIdKeyMapTests.cs | 3 +- 2 files changed, 144 insertions(+), 13 deletions(-) diff --git a/src/Umbraco.Core/Cache/Refreshers/Implement/ContentCacheRefresher.cs b/src/Umbraco.Core/Cache/Refreshers/Implement/ContentCacheRefresher.cs index b8da38e890e3..365c8c6e013a 100644 --- a/src/Umbraco.Core/Cache/Refreshers/Implement/ContentCacheRefresher.cs +++ b/src/Umbraco.Core/Cache/Refreshers/Implement/ContentCacheRefresher.cs @@ -1,3 +1,4 @@ +using System.ComponentModel; using Microsoft.Extensions.DependencyInjection; using Umbraco.Cms.Core.DependencyInjection; using Umbraco.Cms.Core.Events; @@ -38,7 +39,7 @@ public sealed class ContentCacheRefresher : PayloadCacheRefresherBase /// Initializes a new instance of the class. @@ -58,7 +59,8 @@ public ContentCacheRefresher( IContentService contentService, IDocumentPublishStatusManagementService publishStatusManagementService, IDocumentCacheService documentCacheService, - ICacheManager cacheManager) + ICacheManager cacheManager, + IPublishedContentTypeCache publishedContentTypeCache) : base(appCaches, serializer, eventAggregator, factory) { _idKeyMap = idKeyMap; @@ -71,6 +73,7 @@ public ContentCacheRefresher( _contentService = contentService; _documentCacheService = documentCacheService; _publishStatusManagementService = publishStatusManagementService; + _publishedContentTypeCache = publishedContentTypeCache; // TODO: Ideally we should inject IElementsCache // this interface is in infrastructure, and changing this is very breaking @@ -79,6 +82,46 @@ public ContentCacheRefresher( _cacheManager = cacheManager; } + /// + /// Initializes a new instance of the class. + /// + [Obsolete("Please use the non-obsolete constructor. Scheduled for removal in Umbraco 19.")] + public ContentCacheRefresher( + AppCaches appCaches, + IJsonSerializer serializer, + IIdKeyMap idKeyMap, + IDomainService domainService, + IEventAggregator eventAggregator, + ICacheRefresherNotificationFactory factory, + IDocumentUrlService documentUrlService, + IDocumentUrlAliasService documentUrlAliasService, + IDomainCacheService domainCacheService, + IDocumentNavigationQueryService documentNavigationQueryService, + IDocumentNavigationManagementService documentNavigationManagementService, + IContentService contentService, + IDocumentPublishStatusManagementService publishStatusManagementService, + IDocumentCacheService documentCacheService, + ICacheManager cacheManager) + : this( + appCaches, + serializer, + idKeyMap, + domainService, + eventAggregator, + factory, + documentUrlService, + documentUrlAliasService, + domainCacheService, + documentNavigationQueryService, + documentNavigationManagementService, + contentService, + publishStatusManagementService, + documentCacheService, + cacheManager, + StaticServiceProvider.Instance.GetRequiredService()) + { + } + /// /// Initializes a new instance of the class. /// @@ -113,14 +156,15 @@ public ContentCacheRefresher( contentService, StaticServiceProvider.Instance.GetRequiredService(), documentCacheService, - cacheManager) + cacheManager, + StaticServiceProvider.Instance.GetRequiredService()) { } /// /// Initializes a new instance of the class. /// - [Obsolete("Please use the non-obsolete constructor instead. Scheduled for removal in Umbraco 19.")] + [Obsolete("Please use the non-obsolete constructor. Scheduled for removal in Umbraco 19.")] public ContentCacheRefresher( AppCaches appCaches, IJsonSerializer serializer, @@ -152,14 +196,56 @@ public ContentCacheRefresher( contentService, StaticServiceProvider.Instance.GetRequiredService(), documentCacheService, - cacheManager) + cacheManager, + StaticServiceProvider.Instance.GetRequiredService()) + { + } + + /// + /// Initializes a new instance of the class. + /// + [Obsolete("Please use the non-obsolete constructor. Scheduled for removal in Umbraco 19.")] + public ContentCacheRefresher( + AppCaches appCaches, + IJsonSerializer serializer, + IIdKeyMap idKeyMap, + IDomainService domainService, + IEventAggregator eventAggregator, + ICacheRefresherNotificationFactory factory, + IDocumentUrlService documentUrlService, + IDocumentUrlAliasService documentUrlAliasService, + IDomainCacheService domainCacheService, + IDocumentNavigationQueryService documentNavigationQueryService, + IDocumentNavigationManagementService documentNavigationManagementService, + IContentService contentService, + IPublishStatusManagementService publishStatusManagementService, + IDocumentCacheService documentCacheService, + ICacheManager cacheManager, + IPublishedContentTypeCache publishedContentTypeCache) + : this( + appCaches, + serializer, + idKeyMap, + domainService, + eventAggregator, + factory, + documentUrlService, + documentUrlAliasService, + domainCacheService, + documentNavigationQueryService, + documentNavigationManagementService, + contentService, + StaticServiceProvider.Instance.GetRequiredService(), + documentCacheService, + cacheManager, + publishedContentTypeCache) { } /// /// Initializes a new instance of the class. /// - [Obsolete("Please use the non-obsolete constructor instead. Scheduled for removal in Umbraco 19.")] + [Obsolete("Please use the non-obsolete constructor. Scheduled for removal in Umbraco 19.")] public ContentCacheRefresher( AppCaches appCaches, IJsonSerializer serializer, @@ -192,14 +278,58 @@ public ContentCacheRefresher( contentService, documentPublishStatusManagementService, documentCacheService, - cacheManager) + cacheManager, + StaticServiceProvider.Instance.GetRequiredService()) { } - // TODO (V19): Inject IPublishedContentTypeCache through the constructor. In 18.x a constructor taking it would be - // ambiguous for the container next to the obsolete constructor taking both publish status services. - private IPublishedContentTypeCache PublishedContentTypeCache - => _publishedContentTypeCache ??= StaticServiceProvider.Instance.GetRequiredService(); + /// + /// Initializes a new instance of the class. + /// + /// + /// This constructor exists solely to disambiguate DI container constructor resolution between the new + /// and the existing obsolete constructors; all parameters except those forwarded to the non-obsolete + /// constructor are ignored. + /// + [Obsolete("Please use the non-obsolete constructor. Scheduled for removal in Umbraco 19.")] + [EditorBrowsable(EditorBrowsableState.Never)] + public ContentCacheRefresher( + AppCaches appCaches, + IJsonSerializer serializer, + IIdKeyMap idKeyMap, + IDomainService domainService, + IEventAggregator eventAggregator, + ICacheRefresherNotificationFactory factory, + IDocumentUrlService documentUrlService, + IDocumentUrlAliasService documentUrlAliasService, + IDomainCacheService domainCacheService, + IDocumentNavigationQueryService documentNavigationQueryService, + IDocumentNavigationManagementService documentNavigationManagementService, + IContentService contentService, + IPublishStatusManagementService publishStatusManagementService, + IDocumentPublishStatusManagementService documentPublishStatusManagementService, + IDocumentCacheService documentCacheService, + ICacheManager cacheManager, + IPublishedContentTypeCache publishedContentTypeCache) + : this( + appCaches, + serializer, + idKeyMap, + domainService, + eventAggregator, + factory, + documentUrlService, + documentUrlAliasService, + domainCacheService, + documentNavigationQueryService, + documentNavigationManagementService, + contentService, + documentPublishStatusManagementService, + documentCacheService, + cacheManager, + publishedContentTypeCache) + { + } #region Indirect @@ -285,7 +415,7 @@ public override void Refresh(JsonPayload[] payloads) // before and the reload has no effect on anything the content type governs. if (payloads.Any(x => x.ChangeTypes.HasType(TreeChangeTypes.RefreshAll))) { - PublishedContentTypeCache.ClearAll(); + _publishedContentTypeCache.ClearAll(); } var idsRemoved = new HashSet(); diff --git a/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Cache/ContentCacheRefresherIdKeyMapTests.cs b/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Cache/ContentCacheRefresherIdKeyMapTests.cs index 589f27fbc657..1ab217b5cedc 100644 --- a/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Cache/ContentCacheRefresherIdKeyMapTests.cs +++ b/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Cache/ContentCacheRefresherIdKeyMapTests.cs @@ -68,6 +68,7 @@ private ContentCacheRefresher CreateRefresher() Mock.Of(), Mock.Of(), Mock.Of(), - Mock.Of(x => x.ElementsCache == Mock.Of())); + Mock.Of(x => x.ElementsCache == Mock.Of()), + Mock.Of()); } }