Skip to content
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,7 @@ public async Task<IActionResult> 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
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,38 @@
using System.Diagnostics;
using Microsoft.AspNetCore.Mvc.Filters;

namespace Umbraco.Cms.Api.Management.Filters;

/// <summary>
/// An action filter that delays the response until a minimum amount of time has elapsed since the action started executing.
/// </summary>
/// <remarks>
/// 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.
/// </remarks>
internal abstract class EnsureMinimumResponseTimeFilter : IAsyncActionFilter
{
private readonly TimeSpan _minimumResponseTime;
private readonly TimeProvider _timeProvider;

protected EnsureMinimumResponseTimeFilter(TimeSpan minimumResponseTime) => _minimumResponseTime = minimumResponseTime;
/// <summary>
/// Initializes a new instance of the <see cref="EnsureMinimumResponseTimeFilter"/> class using the system clock.
/// </summary>
/// <param name="minimumResponseTime">The minimum time a response takes, measured from when the action starts executing.</param>
protected EnsureMinimumResponseTimeFilter(TimeSpan minimumResponseTime)
: this(minimumResponseTime, TimeProvider.System)
{
}

/// <summary>
/// Initializes a new instance of the <see cref="EnsureMinimumResponseTimeFilter"/> class.
/// </summary>
/// <param name="minimumResponseTime">The minimum time a response takes, measured from when the action starts executing.</param>
/// <param name="timeProvider">The time provider used to measure the elapsed time and to delay the response.</param>
protected EnsureMinimumResponseTimeFilter(TimeSpan minimumResponseTime, TimeProvider timeProvider)
{
_minimumResponseTime = minimumResponseTime;
_timeProvider = timeProvider;
}

/// <summary>
/// Ensures that the action execution takes at least a minimum amount of time by delaying the response if necessary.
Expand All @@ -17,17 +42,14 @@ internal abstract class EnsureMinimumResponseTimeFilter : IAsyncActionFilter
/// <returns>A task that represents the asynchronous operation.</returns>
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);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -67,4 +67,10 @@ public async Task<Attempt<Uri, UserOperationStatus>> CreateForgotPasswordUriAsyn

return Attempt.SucceedWithStatus(UserOperationStatus.Success, uriBuilder.Uri);
}

/// <inheritdoc/>
public Task<Attempt<UserOperationStatus>> CanCreateForgotPasswordUriAsync()
=> Task.FromResult(_hostingEnvironment.ApplicationMainUrl is null
? Attempt.Fail(UserOperationStatus.ApplicationUrlNotConfigured)
: Attempt.Succeed(UserOperationStatus.Success));
}
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
private readonly ICacheManager _cacheManager;
private readonly IDocumentPublishStatusManagementService _publishStatusManagementService;
private readonly IIdKeyMap _idKeyMap;
private IPublishedContentTypeCache? _publishedContentTypeCache;

/// <summary>
/// Initializes a new instance of the <see cref="ContentCacheRefresher"/> class.
Expand Down Expand Up @@ -195,6 +196,11 @@
{
}

// TODO (V19): Inject IPublishedContentTypeCache through the constructor. In 18.x a constructor taking it would be

Check warning on line 199 in src/Umbraco.Core/Cache/Refreshers/Implement/ContentCacheRefresher.cs

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Complete the task associated to this 'TODO' comment.

See more on https://sonarcloud.io/project/issues?id=umbraco_Umbraco-CMS&issues=AaEgxjbTQRNFsK2v8qsh&open=AaEgxjbTQRNFsK2v8qsh&pullRequest=24156
// ambiguous for the container next to the obsolete constructor taking both publish status services.
private IPublishedContentTypeCache PublishedContentTypeCache
=> _publishedContentTypeCache ??= StaticServiceProvider.Instance.GetRequiredService<IPublishedContentTypeCache>();

#region Indirect

/// <summary>
Expand Down Expand Up @@ -273,6 +279,15 @@
/// <inheritdoc/>
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<int>();

foreach (JsonPayload payload in payloads)
Expand Down
16 changes: 16 additions & 0 deletions src/Umbraco.Core/Security/IForgotPasswordUriProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,5 +13,21 @@
/// </summary>
/// <param name="user">The user to create the forgot password URI for.</param>
/// <returns>An attempt containing the generated URI or an error status.</returns>
/// <remarks>
/// Failures that do not depend on the user should also be reported by
/// <see cref="CanCreateForgotPasswordUriAsync" />, so they are reported the same way whether or not the email
/// belongs to a user.
/// </remarks>
Task<Attempt<Uri, UserOperationStatus>> CreateForgotPasswordUriAsync(IUser user);

/// <summary>
/// Determines whether forgot password URIs can currently be created, regardless of the user they are for.
/// </summary>
/// <returns>A successful attempt, or a failed attempt with the reason URIs cannot be created.</returns>
/// <remarks>
/// This is checked before the user is looked up, so the outcome must not depend on any particular user.
/// </remarks>
// TODO (V19): Remove the default implementation.

Check warning on line 30 in src/Umbraco.Core/Security/IForgotPasswordUriProvider.cs

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Complete the task associated to this 'TODO' comment.

See more on https://sonarcloud.io/project/issues?id=umbraco_Umbraco-CMS&issues=AaEgxjaCQRNFsK2v8qsg&open=AaEgxjaCQRNFsK2v8qsg&pullRequest=24156
Task<Attempt<UserOperationStatus>> CanCreateForgotPasswordUriAsync()
=> Task.FromResult(Attempt.Succeed(UserOperationStatus.Success));
}
109 changes: 94 additions & 15 deletions src/Umbraco.Core/Services/ContentTypeServiceBase{TRepository,TItem}.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using System.Globalization;

Check notice on line 1 in src/Umbraco.Core/Services/ContentTypeServiceBase{TRepository,TItem}.cs

View check run for this annotation

CodeScene Delta Analysis / CodeScene Code Health Review (main)

✅ Getting better: Primitive Obsession

The ratio of primitive types in function arguments decreases from 59.09% to 58.93%, threshold = 30.0% The functions in this file have too many primitive types (e.g. int, double, float) in their function argument lists. Using many primitive types lead to the code smell Primitive Obsession. Avoid adding more primitive arguments.
using System.Runtime.InteropServices;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
Expand Down Expand Up @@ -344,191 +344,213 @@
{
// 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
// instead of IsPropertyDirty() since dirty properties have been reset already

var changes = new List<ContentTypeChange<TItem>>();

// 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<int, TItem>? 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<int>();
var rawDataUnaffectedCandidateIds = new HashSet<int>();

foreach (TItem contentType in contentTypes)
{
var dirty = (IRememberBeingDirty)contentType;

// skip new content types
// TODO: This used to be WasPropertyDirty("HasIdentity") but i don't think that actually worked for detecting new entities this does seem to work properly
var isNewContentType = dirty.WasPropertyDirty("Id");
if (isNewContentType)
{
AddChange(changes, contentType, ContentTypeChangeTypes.Create);
continue;
}

// alias change?
var hasAliasChanged = dirty.WasPropertyDirty("Alias");

// existing property alias change?
var hasAnyPropertyChangedAlias = contentType.PropertyTypes.Any(propertyType =>
{
// skip new properties
// TODO: This used to be WasPropertyDirty("HasIdentity") but i don't think that actually worked for detecting new entities this does seem to work properly
var isNewProperty = propertyType.WasPropertyDirty("Id");
if (isNewProperty)
{
return false;
}

// alias change?
return propertyType.WasPropertyDirty("Alias");
});

// removed properties?
var hasAnyPropertyBeenRemoved = dirty.WasPropertyDirty("HasPropertyTypeBeenRemoved");

// removed compositions?
var hasAnyCompositionBeenRemoved = dirty.WasPropertyDirty("HasCompositionTypeBeenRemoved");

// variation changed?
var hasContentTypeVariationChanged = dirty.WasPropertyDirty("Variations");

// property variation change?
var hasAnyPropertyVariationChanged = contentType.WasPropertyTypeVariationChanged();

// A composition change dirties the composition collection (add or remove). Both directions change the
// set of properties this content type - and every type composed of or inheriting from it - exposes, so
// it is a main-impact change that must refresh this type and its descendants. Whether it also needs a
// raw cmsContentNu rebuild is decided separately below: an addition on its own does not (its aliases
// have no stored values yet), but a removal - or an addition that reintroduces a just-removed alias -
// does. See the rawDataAffected calculation.
var hasCompositionChanged = dirty.WasPropertyDirty("ContentTypeComposition");

// Detect all granular change types independently so that structural
// and non-structural changes can be detected in the same operation
// (e.g. removing a property AND adding another at the same time).
var hasAnyChange = false;

// --- Structural changes (each includes RefreshMain automatically) ---

if (hasAliasChanged)
{
AddChange(changes, contentType, ContentTypeChangeTypes.AliasChanged);
hasAnyChange = true;
}

if (hasAnyPropertyChangedAlias)
{
AddChange(changes, contentType, ContentTypeChangeTypes.PropertyAliasChanged);
hasAnyChange = true;
}

if (hasAnyPropertyBeenRemoved)
{
AddChange(changes, contentType, ContentTypeChangeTypes.PropertyRemoved);
hasAnyChange = true;
}

if (hasAnyCompositionBeenRemoved)
{
AddChange(changes, contentType, ContentTypeChangeTypes.CompositionRemoved);
hasAnyChange = true;
}

if (hasAnyPropertyVariationChanged)
{
AddChange(changes, contentType, ContentTypeChangeTypes.PropertyVariationChanged);
hasAnyChange = true;
}

// Add VariationChanged flag if content type variation changed.
// This is used by DocumentUrlService to rebuild URL cache with correct languageId.
if (hasContentTypeVariationChanged)
{
AddChange(changes, contentType, ContentTypeChangeTypes.VariationChanged);
hasAnyChange = true;
}

// compositions added? Constructive in itself, but relevant to the raw-data check below: adding a
// composition can reintroduce a just-removed property alias behind a different property type.
var hasAnyCompositionBeenAdded = dirty.WasPropertyDirty("HasCompositionTypeBeenAdded");

// main impact on properties? Propagate RefreshMain to composed types.
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)
{
// A composition change alone (add or remove) needs RefreshMain even when none of the granular
// flags above fired for it.
AddChange(changes, contentType, ContentTypeChangeTypes.RefreshMain);
hasAnyChange = true;
(rawDataUnaffected ? rawDataUnaffectedCandidateIds : rebuildRequiredIds).Add(contentType.Id);
}

if (hasPropertyMainImpact)
{
foreach (TItem c in GetComposedOf(contentType.Id))
{
// Composing types inherit the same property change, so they share its rebuild requirement.
AddChange(changes, c, ContentTypeChangeTypes.RefreshMain);
(rawDataUnaffected ? rawDataUnaffectedCandidateIds : rebuildRequiredIds).Add(c.Id);
}
}

// --- Non-structural changes (each includes RefreshOther automatically) ---

// new properties added?
var hasAnyPropertyBeenAdded = contentType.PropertyTypes.Any(pt => pt.WasPropertyDirty("Id"));
if (hasAnyPropertyBeenAdded)
{
AddChange(changes, contentType, ContentTypeChangeTypes.PropertyAdded);
hasAnyChange = true;
}

if (hasAnyCompositionBeenAdded)
{
AddChange(changes, contentType, ContentTypeChangeTypes.CompositionAdded);
hasAnyChange = true;
}

// Fall back to bare RefreshOther if none of the specific checks matched
// (e.g. for changes we haven't categorized yet).
if (!hasAnyChange)
{
AddChange(changes, contentType, ContentTypeChangeTypes.RefreshOther);
}

// 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))
{
if (hasPropertyMainImpact)
{
// 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);
}
}
}

Check warning on line 553 in src/Umbraco.Core/Services/ContentTypeServiceBase{TRepository,TItem}.cs

View check run for this annotation

CodeScene Delta Analysis / CodeScene Code Health Review (main)

❌ Getting worse: Complex Method

ComposeContentTypeChanges increases in cyclomatic complexity from 35 to 39, threshold = 9 This function has many conditional statements (e.g. if, for, while), leading to lower code health. Avoid adding more conditionals and code to it without refactoring.

Check warning on line 553 in src/Umbraco.Core/Services/ContentTypeServiceBase{TRepository,TItem}.cs

View check run for this annotation

CodeScene Delta Analysis / CodeScene Code Health Review (main)

❌ Getting worse: Complex Conditional

ComposeContentTypeChanges increases from 1 complex conditionals with 2 branches to 2 complex conditionals with 4 branches, threshold = 2 A complex conditional is an expression inside a branch (e.g. if, for, while) which consists of multiple, logical operators such as AND/OR. The more logical operators in an expression, the more severe the code smell.

Check warning on line 553 in src/Umbraco.Core/Services/ContentTypeServiceBase{TRepository,TItem}.cs

View check run for this annotation

CodeScene Delta Analysis / CodeScene Code Health Review (main)

❌ New issue: Deep, Nested Complexity

ComposeContentTypeChanges has a nested complexity depth of 4, threshold = 4 This function contains deeply nested logic such as if statements and/or loops. The deeper the nesting, the lower the code health.
}

// Flag the raw data as unaffected only for types that were never independently marked as needing a
Expand Down Expand Up @@ -767,8 +789,65 @@
return GetComposedOf(id, allContentTypes);
}

/// <summary>
/// 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).
/// </summary>
/// <returns>The lookup of directly referencing content types, keyed by referenced content type id.</returns>
/// <remarks>
/// 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.
/// </remarks>
private ILookup<int, TItem> GetDirectReferencingTypes() =>
GetAll()
.SelectMany(
contentType => contentType.ContentTypeComposition,
(contentType, referenced) => (ReferencedId: referenced.Id, ContentType: contentType))
.ToLookup(x => x.ReferencedId, x => x.ContentType);

/// <summary>
/// Gets every content type whose effective property set derives from the specified content type, directly
/// or indirectly.
/// </summary>
/// <param name="id">The identifier of the content type.</param>
/// <param name="directReferencingTypes">
/// The content types that directly reference each content type, as built by
/// <see cref="GetDirectReferencingTypes" />.
/// </param>
/// <returns>The content types deriving from the specified content type.</returns>
/// <remarks>
/// 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
/// <see cref="IContentTypeComposition.CompositionPropertyTypes" /> and
/// <see cref="IContentTypeComposition.CompositionAliases()" />), so a change to one content type is a change
/// to everything deriving from it, not just to its direct consumers.
/// </remarks>
private static TItem[] GetComposedOfTransitive(int id, ILookup<int, TItem> directReferencingTypes)

Check warning on line 826 in src/Umbraco.Core/Services/ContentTypeServiceBase{TRepository,TItem}.cs

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Static members should appear before non-static members

See more on https://sonarcloud.io/project/issues?id=umbraco_Umbraco-CMS&issues=AaEgxjX6QRNFsK2v8qsf&open=AaEgxjX6QRNFsK2v8qsf&pullRequest=24156
{
var composedOf = new Dictionary<int, TItem>();
var remaining = new Stack<int>();
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)

Check warning on line 837 in src/Umbraco.Core/Services/ContentTypeServiceBase{TRepository,TItem}.cs

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Remove the unnecessary Boolean literal(s).

See more on https://sonarcloud.io/project/issues?id=umbraco_Umbraco-CMS&issues=AaEgxjX6QRNFsK2v8qsd&open=AaEgxjX6QRNFsK2v8qsd&pullRequest=24156
{
continue;
}

remaining.Push(contentType.Id);
}
}

return [.. composedOf.Values];
}

/// <inheritdoc />
public int Count()

Check warning on line 850 in src/Umbraco.Core/Services/ContentTypeServiceBase{TRepository,TItem}.cs

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

'public' members should come before 'private' members

See more on https://sonarcloud.io/project/issues?id=umbraco_Umbraco-CMS&issues=AaEgxjX6QRNFsK2v8qse&open=AaEgxjX6QRNFsK2v8qse&pullRequest=24156
{
using ICoreScope scope = ScopeProvider.CreateCoreScope(autoComplete: true);
scope.ReadLock(ReadLockIds);
Expand Down
8 changes: 7 additions & 1 deletion src/Umbraco.Core/Services/UserService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -664,6 +664,13 @@

ICoreBackOfficeUserManager userManager = serviceScope.ServiceProvider.GetRequiredService<ICoreBackOfficeUserManager>();
IBackOfficeUserStore userStore = serviceScope.ServiceProvider.GetRequiredService<IBackOfficeUserStore>();
IForgotPasswordUriProvider uriProvider = serviceScope.ServiceProvider.GetRequiredService<IForgotPasswordUriProvider>();

Attempt<UserOperationStatus> canCreateUriAttempt = await uriProvider.CanCreateForgotPasswordUriAsync();
if (canCreateUriAttempt.Success is false)

Check warning on line 670 in src/Umbraco.Core/Services/UserService.cs

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Remove the unnecessary Boolean literal(s).

See more on https://sonarcloud.io/project/issues?id=umbraco_Umbraco-CMS&issues=AaEgxjOPQRNFsK2v8qsc&open=AaEgxjOPQRNFsK2v8qsc&pullRequest=24156
{
return Attempt.Fail(canCreateUriAttempt.Result);
}

IUser? user = await userStore.GetByEmailAsync(userEmail);

Expand All @@ -672,7 +679,6 @@
return Attempt.Fail(UserOperationStatus.UserNotFound);
}

IForgotPasswordUriProvider uriProvider = serviceScope.ServiceProvider.GetRequiredService<IForgotPasswordUriProvider>();
Attempt<Uri, UserOperationStatus> uriAttempt = await uriProvider.CreateForgotPasswordUriAsync(user);
if (uriAttempt.Success is false)
{
Expand Down
Loading
Loading