diff --git a/CLAUDE.md b/CLAUDE.md index 785702fa30a1..5260f9569841 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -404,6 +404,20 @@ When updating dependencies, decide which file the package belongs in: - `.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 7447a77dc314..6a4f704b709b 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 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/Cache/Refreshers/Implement/ContentCacheRefresher.cs b/src/Umbraco.Core/Cache/Refreshers/Implement/ContentCacheRefresher.cs index 25928f9194e5..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,6 +39,7 @@ public sealed class ContentCacheRefresher : PayloadCacheRefresherBase /// Initializes a new instance of the class. @@ -57,7 +59,8 @@ public ContentCacheRefresher( IContentService contentService, IDocumentPublishStatusManagementService publishStatusManagementService, IDocumentCacheService documentCacheService, - ICacheManager cacheManager) + ICacheManager cacheManager, + IPublishedContentTypeCache publishedContentTypeCache) : base(appCaches, serializer, eventAggregator, factory) { _idKeyMap = idKeyMap; @@ -70,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 @@ -78,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. /// @@ -112,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, @@ -151,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, @@ -191,7 +278,56 @@ public ContentCacheRefresher( contentService, documentPublishStatusManagementService, documentCacheService, - cacheManager) + cacheManager, + 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) { } @@ -273,6 +409,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/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/ContentTypeServiceBase{TRepository,TItem}.cs b/src/Umbraco.Core/Services/ContentTypeServiceBase{TRepository,TItem}.cs index 7b00356606aa..1a54d39dd89f 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(); @@ -497,16 +502,6 @@ internal IEnumerable> ComposeContentTypeChanges(params (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? @@ -529,6 +524,33 @@ internal IEnumerable> ComposeContentTypeChanges(params { 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); + } + } + } } // Flag the raw data as unaffected only for types that were never independently marked as needing a @@ -767,6 +789,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/src/Umbraco.Core/Services/UserService.cs b/src/Umbraco.Core/Services/UserService.cs index eda163bb6062..53a88ee601e9 100644 --- a/src/Umbraco.Core/Services/UserService.cs +++ b/src/Umbraco.Core/Services/UserService.cs @@ -664,6 +664,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); @@ -672,7 +679,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/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 f9430a9131ff..ccefcfa54363 100644 --- a/tests/Umbraco.Tests.Integration/Umbraco.Core/Services/ContentTypeEditingServiceTests.Update.cs +++ b/tests/Umbraco.Tests.Integration/Umbraco.Core/Services/ContentTypeEditingServiceTests.Update.cs @@ -867,6 +867,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.PropertyAdded); + 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.PropertyVariationChanged); + 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.PropertyRemoved | 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() { @@ -1525,13 +1620,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] @@ -1806,6 +1903,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.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.Integration/Umbraco.PublishedCache.HybridCache/DocumentHybridCacheDocumentTypeTests.cs b/tests/Umbraco.Tests.Integration/Umbraco.PublishedCache.HybridCache/DocumentHybridCacheDocumentTypeTests.cs index 89b66ecb1995..4ef37b1a6db2 100644 --- a/tests/Umbraco.Tests.Integration/Umbraco.PublishedCache.HybridCache/DocumentHybridCacheDocumentTypeTests.cs +++ b/tests/Umbraco.Tests.Integration/Umbraco.PublishedCache.HybridCache/DocumentHybridCacheDocumentTypeTests.cs @@ -167,6 +167,84 @@ public async Task Multi_Type_Change_Does_Not_Flag_A_Type_That_Independently_Requ }); } + /// + /// 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); + + // Add a property to both compositions. Saving gives each new property its Id, which is how a property + // addition is detected, and the saved types remember that state for the classification below. + AddTextBoxProperty(compositionA, "addedPropA"); + AddTextBoxProperty(compositionB, "addedPropB"); + await ContentTypeService.UpdateAsync(compositionA, Constants.Security.SuperUserKey); + await ContentTypeService.UpdateAsync(compositionB, Constants.Security.SuperUserKey); + + // Act - classify both types in a single call, as one save covering both would. There's no public batch + // save, so call the classification directly. + var service = (global::Umbraco.Cms.Core.Services.ContentTypeService)ContentTypeService; + List> changes = service.ComposeContentTypeChanges(compositionA, compositionB).ToList(); + + // Assert + Assert.That(changes.Count(c => c.Item.Id == composing.Id), Is.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.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() { 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()); } }