Files

368 lines
15 KiB
C#
Raw Permalink Normal View History

using System.Linq.Expressions;
using System.Reflection;
V14: Add authorization policies to Management API controllers - p2 (#15211) * Making ProblemDetails details more generic * Adding authorizer that can be replaces for external authz in handlers. Adding handler and requirement for UserBelongsToUserGroupInRequest policy * Adding method to get the GUID from claims * Adding service methods to check user group authz * Porting MustSatisfyRequirementAuthorizationHandler * Adding controllers authz * Fix return status code + produced response type * Moving to folder * Adding DenyLocalLogin policy scaffold * Implement a temp DenyLocalLoginHandler * Introducing a new Fobidden result * Fix comment * Introducing a helper class for authorizers * Changed nullability for GetCurrentUser * Changes from Attempt to Status + FIXME comments * Create a UserGroupAuthorizationStatus to be used in the future * Introduces a new authz status for checking media acess * Introducing a new permission service for media * Adding fixme * Adding more policy configurations * Adding Media policy requirement and handler * Adding media authorizer * Fix order of params * Adding duplicate code comment * Adding authz to media controllers * Migrating more logic from MediaPermissions.cs * Adding more MediaAuthorizationStatus-es * Handling of new authorization status * Fix comment * Adding NotFound case * Adding NewDenyLocalLoginIfConfigured policy && commenting [AllowAnonymous] where the policy is applied since it is already handled * Changed Forbid() to Forbidden() to get the correct status code * Remove policy that is applied on the base controller already * Implement and apply NewUmbracoFeatureEnabled policy * Renaming classes to add Permission in the name * Register permission services * Add FIXME * Introduce new IUserGroupPermissionService and refactor accordingly * Add single overload with default implementation * Adding user permission policy and related * Applying admin policy * Register all new policies * Better wording * Add default implementation for a single overload * Adding remarks to IContentPermissionService.cs * Supporting null as key in ContentPermissionService * Fix namespace * Reverting back to not supporting null as content key, but having dedicated implementation * Adding content authorizer with null values to represent root item * Removing null key support and adding dedicated implementation * Removing remarks * Adding content resource with null support * Removing null support * Adding requirement and status * Adding content authorizer + handlers * Applying policies to content controllers * Update comment * Handling of Authorization Statuses * More authz in controllers * Fix comments * New branch handler * Obsolete old implementation * Adding dedicated policies to root and bin * Adding a branch specific namespace * Bin specific requirement and namespace * Root specific requirement and namespace * Changing to new root policy * Refactoring * Save policies * Fix null check/reference * Add TODO comment * Create media root- and bin-specific policies, handlers, etc. * Apply correct policy in create and update media controllers * Apply root policy to move and sort controllers * Fix wording * Adding UserGroupAuthorizationStatusResult * Remove all AuthorizationStatusResult as we cannot get the specific AuthorizationStatus * Fixing Umbraco feature policy * Fix allow anonymous endpoints - the value returned from DenyLocalLoginHandler wasn't enough, we need to succeed DenyAnonymousAuthorizationRequirement as it is required for some of the endpoints that had the attribute * Apply DenyLocalLoginIfConfigured policy to corresponding re-implementation of PostSetInvitedUserPassword * Fix comment * Renaming performingUser to user and fixing comments * Rename helper method * Fix references * Re-add merge conflict deletion * Adding Backoffice requirement and relevant * Registering * Added a simple policy test * Fixed small test things and clean up * Temp solution * Added one more test and fix another static issue * Fix another merge conflict * Remove BackOfficePermissionRequirement and handler as they might not be necessary * Comment out again [AllowAnonymous] * Remove AuthorizationPolicies.BackOfficeAccessWithoutApproval policy as it might not be necessary * Fix temp implementation * Fix reference to correct handler * Apply authz policy to new publish/unpublish controllers * Fix comments * Removing duplicate ProducesResponseTypes * Added swagger documentation about the 401 and 403 * Added Resources to Media, User and UserGroup * Handle root, recycle bin and branch in the same handler * Handle both parent and target when moving * Check Ids for all sort requests * Xml docs * Clean up * Clean up * Fix build * Cleanup * Remove TODO * Added missing overload * Use yield * Adding some keys to check --------- Co-authored-by: Bjarke Berg <mail@bergmania.dk> Co-authored-by: Andreas Zerbst <andr317c@live.dk>
2023-12-11 08:25:29 +01:00
using Asp.Versioning;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.AspNetCore.Routing;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Moq;
using NUnit.Framework;
V14: Add authorization policies to Management API controllers - p2 (#15211) * Making ProblemDetails details more generic * Adding authorizer that can be replaces for external authz in handlers. Adding handler and requirement for UserBelongsToUserGroupInRequest policy * Adding method to get the GUID from claims * Adding service methods to check user group authz * Porting MustSatisfyRequirementAuthorizationHandler * Adding controllers authz * Fix return status code + produced response type * Moving to folder * Adding DenyLocalLogin policy scaffold * Implement a temp DenyLocalLoginHandler * Introducing a new Fobidden result * Fix comment * Introducing a helper class for authorizers * Changed nullability for GetCurrentUser * Changes from Attempt to Status + FIXME comments * Create a UserGroupAuthorizationStatus to be used in the future * Introduces a new authz status for checking media acess * Introducing a new permission service for media * Adding fixme * Adding more policy configurations * Adding Media policy requirement and handler * Adding media authorizer * Fix order of params * Adding duplicate code comment * Adding authz to media controllers * Migrating more logic from MediaPermissions.cs * Adding more MediaAuthorizationStatus-es * Handling of new authorization status * Fix comment * Adding NotFound case * Adding NewDenyLocalLoginIfConfigured policy && commenting [AllowAnonymous] where the policy is applied since it is already handled * Changed Forbid() to Forbidden() to get the correct status code * Remove policy that is applied on the base controller already * Implement and apply NewUmbracoFeatureEnabled policy * Renaming classes to add Permission in the name * Register permission services * Add FIXME * Introduce new IUserGroupPermissionService and refactor accordingly * Add single overload with default implementation * Adding user permission policy and related * Applying admin policy * Register all new policies * Better wording * Add default implementation for a single overload * Adding remarks to IContentPermissionService.cs * Supporting null as key in ContentPermissionService * Fix namespace * Reverting back to not supporting null as content key, but having dedicated implementation * Adding content authorizer with null values to represent root item * Removing null key support and adding dedicated implementation * Removing remarks * Adding content resource with null support * Removing null support * Adding requirement and status * Adding content authorizer + handlers * Applying policies to content controllers * Update comment * Handling of Authorization Statuses * More authz in controllers * Fix comments * New branch handler * Obsolete old implementation * Adding dedicated policies to root and bin * Adding a branch specific namespace * Bin specific requirement and namespace * Root specific requirement and namespace * Changing to new root policy * Refactoring * Save policies * Fix null check/reference * Add TODO comment * Create media root- and bin-specific policies, handlers, etc. * Apply correct policy in create and update media controllers * Apply root policy to move and sort controllers * Fix wording * Adding UserGroupAuthorizationStatusResult * Remove all AuthorizationStatusResult as we cannot get the specific AuthorizationStatus * Fixing Umbraco feature policy * Fix allow anonymous endpoints - the value returned from DenyLocalLoginHandler wasn't enough, we need to succeed DenyAnonymousAuthorizationRequirement as it is required for some of the endpoints that had the attribute * Apply DenyLocalLoginIfConfigured policy to corresponding re-implementation of PostSetInvitedUserPassword * Fix comment * Renaming performingUser to user and fixing comments * Rename helper method * Fix references * Re-add merge conflict deletion * Adding Backoffice requirement and relevant * Registering * Added a simple policy test * Fixed small test things and clean up * Temp solution * Added one more test and fix another static issue * Fix another merge conflict * Remove BackOfficePermissionRequirement and handler as they might not be necessary * Comment out again [AllowAnonymous] * Remove AuthorizationPolicies.BackOfficeAccessWithoutApproval policy as it might not be necessary * Fix temp implementation * Fix reference to correct handler * Apply authz policy to new publish/unpublish controllers * Fix comments * Removing duplicate ProducesResponseTypes * Added swagger documentation about the 401 and 403 * Added Resources to Media, User and UserGroup * Handle root, recycle bin and branch in the same handler * Handle both parent and target when moving * Check Ids for all sort requests * Xml docs * Clean up * Clean up * Fix build * Cleanup * Remove TODO * Added missing overload * Use yield * Adding some keys to check --------- Co-authored-by: Bjarke Berg <mail@bergmania.dk> Co-authored-by: Andreas Zerbst <andr317c@live.dk>
2023-12-11 08:25:29 +01:00
using Umbraco.Cms.Api.Delivery.Controllers.Content;
using Umbraco.Cms.Api.Management.Controllers;
using Umbraco.Cms.Api.Management.Controllers.ModelsBuilder;
using Umbraco.Cms.Api.Management.DependencyInjection;
V14: Add authorization policies to Management API controllers - p2 (#15211) * Making ProblemDetails details more generic * Adding authorizer that can be replaces for external authz in handlers. Adding handler and requirement for UserBelongsToUserGroupInRequest policy * Adding method to get the GUID from claims * Adding service methods to check user group authz * Porting MustSatisfyRequirementAuthorizationHandler * Adding controllers authz * Fix return status code + produced response type * Moving to folder * Adding DenyLocalLogin policy scaffold * Implement a temp DenyLocalLoginHandler * Introducing a new Fobidden result * Fix comment * Introducing a helper class for authorizers * Changed nullability for GetCurrentUser * Changes from Attempt to Status + FIXME comments * Create a UserGroupAuthorizationStatus to be used in the future * Introduces a new authz status for checking media acess * Introducing a new permission service for media * Adding fixme * Adding more policy configurations * Adding Media policy requirement and handler * Adding media authorizer * Fix order of params * Adding duplicate code comment * Adding authz to media controllers * Migrating more logic from MediaPermissions.cs * Adding more MediaAuthorizationStatus-es * Handling of new authorization status * Fix comment * Adding NotFound case * Adding NewDenyLocalLoginIfConfigured policy && commenting [AllowAnonymous] where the policy is applied since it is already handled * Changed Forbid() to Forbidden() to get the correct status code * Remove policy that is applied on the base controller already * Implement and apply NewUmbracoFeatureEnabled policy * Renaming classes to add Permission in the name * Register permission services * Add FIXME * Introduce new IUserGroupPermissionService and refactor accordingly * Add single overload with default implementation * Adding user permission policy and related * Applying admin policy * Register all new policies * Better wording * Add default implementation for a single overload * Adding remarks to IContentPermissionService.cs * Supporting null as key in ContentPermissionService * Fix namespace * Reverting back to not supporting null as content key, but having dedicated implementation * Adding content authorizer with null values to represent root item * Removing null key support and adding dedicated implementation * Removing remarks * Adding content resource with null support * Removing null support * Adding requirement and status * Adding content authorizer + handlers * Applying policies to content controllers * Update comment * Handling of Authorization Statuses * More authz in controllers * Fix comments * New branch handler * Obsolete old implementation * Adding dedicated policies to root and bin * Adding a branch specific namespace * Bin specific requirement and namespace * Root specific requirement and namespace * Changing to new root policy * Refactoring * Save policies * Fix null check/reference * Add TODO comment * Create media root- and bin-specific policies, handlers, etc. * Apply correct policy in create and update media controllers * Apply root policy to move and sort controllers * Fix wording * Adding UserGroupAuthorizationStatusResult * Remove all AuthorizationStatusResult as we cannot get the specific AuthorizationStatus * Fixing Umbraco feature policy * Fix allow anonymous endpoints - the value returned from DenyLocalLoginHandler wasn't enough, we need to succeed DenyAnonymousAuthorizationRequirement as it is required for some of the endpoints that had the attribute * Apply DenyLocalLoginIfConfigured policy to corresponding re-implementation of PostSetInvitedUserPassword * Fix comment * Renaming performingUser to user and fixing comments * Rename helper method * Fix references * Re-add merge conflict deletion * Adding Backoffice requirement and relevant * Registering * Added a simple policy test * Fixed small test things and clean up * Temp solution * Added one more test and fix another static issue * Fix another merge conflict * Remove BackOfficePermissionRequirement and handler as they might not be necessary * Comment out again [AllowAnonymous] * Remove AuthorizationPolicies.BackOfficeAccessWithoutApproval policy as it might not be necessary * Fix temp implementation * Fix reference to correct handler * Apply authz policy to new publish/unpublish controllers * Fix comments * Removing duplicate ProducesResponseTypes * Added swagger documentation about the 401 and 403 * Added Resources to Media, User and UserGroup * Handle root, recycle bin and branch in the same handler * Handle both parent and target when moving * Check Ids for all sort requests * Xml docs * Clean up * Clean up * Fix build * Cleanup * Remove TODO * Added missing overload * Use yield * Adding some keys to check --------- Co-authored-by: Bjarke Berg <mail@bergmania.dk> Co-authored-by: Andreas Zerbst <andr317c@live.dk>
2023-12-11 08:25:29 +01:00
using Umbraco.Cms.Core;
using Umbraco.Cms.Core.Cache;
using Umbraco.Cms.Core.Composing;
Auhorization: Cherrypicked integration tests from V15 (#20492) * V15 QA Added the authorization integration tests (#18419) * Added authorization integration tests * Removed unnecessary tests and update tests for preview controller * Updated to use the newest changes from v15/dev and added an override for the AuthenticateClientAsync to use the userGroupKey * Updated CompatibilitySuppressions to include changes from integration tests * Updated pipelines * Skips managementApi tests * Only run necessary tests * Added new schema per fixture to reduce test setup time * Fixed failing tests * Updated test setup * Updated test * Added suppression * Fixed failing tests * Updated addOnTeardown methods to protected * Added method for clearing the host * Added teardown * Updated model usage * Added a lot of cleanup for memory leak issues when running tests * Added CompatibilitySuppressions.xml * Updated tests * Cleaned up * Adjusted base classes * Updated pipeline * Updated CompatibilitySuppressions.xml * Updated test logging * Fixed reponse * Updated condition to skip tests * Updated tests, not done * Reworked test to expect correct responses with correct setup * Updated tests * More updates to tests * Updated tests * Cleaned up tests * Updated setup * Cleaned up tests to match setup * Cleaned up setup * Removed suppression * Fixed tests * Move order of checks * Fix naming * Formatting * Dispose of host * Keep track of if we're disposed * Compat suppression * Dont dispose * Fix failing tests * removed unused virtual * Updated CompatibilitySuppressions.xml --------- Co-authored-by: Andreas Zerbst <andr317c@live.dk> Co-authored-by: Zeegaan <skrivdetud@gmail.com> Co-authored-by: Nikolaj Geisle <70372949+Zeegaan@users.noreply.github.com> # Conflicts: # tests/Umbraco.Tests.Integration/CompatibilitySuppressions.xml # tests/Umbraco.Tests.Integration/ManagementApi/ManagementApiTest.cs # tests/Umbraco.Tests.Integration/ManagementApi/Policies/AllCultureControllerTests.cs # tests/Umbraco.Tests.Integration/ManagementApi/Policies/CreateDocumentTests.cs # tests/Umbraco.Tests.Integration/ManagementApi/Policies/UpdateDocumentTests.cs # tests/Umbraco.Tests.Integration/ManagementApi/Preview/EndPreviewTests.cs # tests/Umbraco.Tests.Integration/ManagementApi/Preview/EnterPreviewTests.cs # tests/Umbraco.Tests.Integration/TestServerTest/UmbracoTestServerTestBase.cs * Updated test * Updates * Removed unnessecary test --------- Co-authored-by: Nhu Dinh <150406148+nhudinh0309@users.noreply.github.com> Co-authored-by: Zeegaan <skrivdetud@gmail.com> Co-authored-by: Nikolaj Geisle <70372949+Zeegaan@users.noreply.github.com>
2025-10-14 12:04:10 +02:00
using Umbraco.Cms.Core.Persistence.Repositories;
using Umbraco.Cms.Core.Services;
using Umbraco.Cms.Core.Web;
v10 SQLite support + distributed locking abstractions (#11922) * Created Persistence.SQLite project skeleton. * SQLite database initialization * Various changes and hacks to make things work. * WIP integration tests * Fix thread safety tests * Fix tests that relied on tie breaker sorting. Spent a fair amount of time looking for a less lazy fix but gave up. * Convert right join to left join ContentTypeRepository.PerformGetByQuery SQLite doesn't support right join * Fix test Can_Generate_Delete_SubQuery_Statement Worth noting that NPoco.DatabaseTypes.SQLiteDatabaseType doesn't override EscapeSqlIdentifier so NPoco will escape with []. SQLite docs say > "A keyword enclosed in square brackets is an identifier. This is not standard SQL. This quoting mechanism is used by MS Access and SQL Server and is included in SQLite for compatibility." Also could have updated SqliteSyntaxProvider to match npoco but decided against it. * Fixes for paginated custom order by * Fix tests broken by lack of unique indexes. * Fix SqlServerTableByTableTest tests. These tests didn't actually do anything as the tables already exist so schema creator just returned. Did however point out that the default implementation for DoesTableExist just returns false so added a default naive implementation. * Fix ValidateLoginSession - SelectTop must come later * dry up database cleanup * Fix up db migration tests. We can't drop pk in sqlite without recreating table. Test looks to be testing that add column works as intended which we can test. * Prevent schema creation errors. * SQLite ignore lock tests, WAL back on. * Fix package schema tests * Fix NPocoFetchTests - case sensitivity not under test * Fix AdvancedMigrationTests (where possible) Migrations probably need a good look later. Maybe nuke old migrations and only support moving to v10 from v9. If we do that can do some cleanup. * Cleanup test database configuration * Run integration tests against SQLite on build agent. * Drop MS.Data.SQLite System.Data.SQLite was quicker to roll out due to more CLR type mapping * YAML * Skip Umbraco.Tests.Integration.SqlCe * Drop SqlServerTableByTable tests. Until this week they did nothing anyway as they with NewSchemaPerTest so the tests all passed as CreateTable was no op (already exists). Also all of the tables are created in an empty database by SchemaValidationTest.cs DatabaseSchemaCreation_Produces_DatabaseSchemaResult_With_Zero_Errors * Might aswell run against macOS also. * Copy azure pipelines task header layout * Delete SQLCe projects * Remove SQL CE specific code. * Remove SQL CE NuSpec, template params, build script setup * Delete umbraco-netcore-only.sln * Add SkipTests solution configuration and use for codeql * Remove reference to deleted nuspec file. * Refactor ConnectionStrings WRT DataDirectory placeholder & ProviderName. At this point you can try out SQLite support by setting the following in appsettings.json and then completing the install process. "ConnectionStrings": { "umbracoDbDSN": "Data Source=|DataDirectory|/umbraco.sqlite", "umbracoDbDSN_ProviderName": "System.Data.SQLite" }, Not currently possible via installer UI without provider name pre-set in configuration. * Switch to Microsoft.Data.Sqlite Some gross hacks but will be good to find out if this works with apple silicon. * Enable selection of SQLite via installer UI (also quick install) * Remove SqlServerDbProviderFactoryCreator to cleanup a TODO * Move SQL Server support to its own class library * Add persistence dependencies to Umbraco.CMS metapackage * Bugfix packages delete query Created invalid query for SQLite. * Try out cypress tests Linux + SQLite * Prevent cypress test artifact upload failure on attempt 2+ * LocalDb bugfixes * Drop redundant enum * Move SqlClient constant * Misc whitespace * Remove IsSqlCe extension (TODO: drop non 9->10 migrations later). * Umbraco.Persistence.* -> Umbraco.Cms.Persistence.* * Display quick install defaults and per provider default database name. * Misc remove old comment * little re-arrange * Remove almost all usages of IsSqlite extension. * visual adjustments * Custom Database Configuration is last step and should then say Install. * use text instead of disabled inputs * move legend, rename to Install * Update SqlMainDomLock to work without distributed locks. * Added IDistributedLockingMechanism interface and in memory impl. * Drop locking from ISqlSyntaxProvider & wire up scope to abstraction. * Added SqlServerDistributedLockingMechanism * Move distributed locking interfaces and exceptions to Core + xmldocs. * Fix tests, Misc cleanup, Add SQL distributed locking integration tests * Provide mechanism to specify DistributedLockingMechanism in config (even if added by composer) * Nomplementation -> NoImplementation * Fix misleading comment * Integration tests use SqlServerDistributedLockingMechanism when possible * Handle up-gradable locks SqlServerDistributedLockingMechanism. TODO: InMemoryDistributedLockingMechanism. Note: Nuked SqlServerDistributedLockingMechanismTests, will still sleep at night. Is covered by Umbraco.Cms.Tests.Integration.Umbraco.Infrastructure.Persistence.LockTests * Make tests pass for InMemoryDistributedLockingMechanism, pretty hacky. * Tweak constraints on WithCollectionBuilder so i can drop bad constructor * Added SqliteDistributedLockingMechanism * Dropped InMemoryDistributedMechanism + magic InMemoryDistributedMechanism was pretty rubbish and now we have a decent implementation for SQLite as we no longer block readers see 8d1f42b. Also drop the CollectionBuilder setup, instead do the same as we do for syntax providers etc, it's more automagical so we never require an explicit selection although we are allowing for it. However keeping the optional IUmbracoBuilder constructor param for CollectionBuilders as it's extremely useful. * Fix quick install "" database name. * Hide Database Configuration section when a connection string is pre-set. Doesn't seem worth it to extract db name from connection string. * Ensure wal test 2+ * Fix logging inconsistencies. * Ensure in transaction when obtaining locks + no-op the SQLite read lock. There's no point in running the query just to make a single test pass. * Fix installer database display names * Allow SQLite shared cache without losing deferred transactions * Opt into shared cache for new SQLite databases + fix filename * Fix misc inconsistency in .gitignore * Prefer our interceptor interface * Restore DEBUG_DATABASES code OnConnectionOpened in case it's used. * Back to private cache. * Added retry strategy for SQLite + refactor out SQL server specific stuff * Fix SQL server tests. * Misc - Orphaned comment, incorrect casing. * InMemory SQLite test database & turn shared cache back on everywhere. Co-authored-by: Niels Lyngsø <niels.lyngso@gmail.com>
2022-03-11 16:14:20 +00:00
using Umbraco.Cms.Persistence.Sqlite;
using Umbraco.Cms.Persistence.SqlServer;
using Umbraco.Cms.Tests.Common.Testing;
using Umbraco.Cms.Tests.Integration.DependencyInjection;
using Umbraco.Cms.Tests.Integration.Testing;
using Umbraco.Cms.Web.Common.Controllers;
using Umbraco.Cms.Web.Website.Controllers;
namespace Umbraco.Cms.Tests.Integration.TestServerTest
{
[TestFixture]
[UmbracoTest(Database = UmbracoTestOptions.Database.NewSchemaPerTest, Logger = UmbracoTestOptions.Logger.Console, Boot = true)]
public abstract class UmbracoTestServerTestBase : UmbracoIntegrationTestBase
{
Auhorization: Cherrypicked integration tests from V15 (#20492) * V15 QA Added the authorization integration tests (#18419) * Added authorization integration tests * Removed unnecessary tests and update tests for preview controller * Updated to use the newest changes from v15/dev and added an override for the AuthenticateClientAsync to use the userGroupKey * Updated CompatibilitySuppressions to include changes from integration tests * Updated pipelines * Skips managementApi tests * Only run necessary tests * Added new schema per fixture to reduce test setup time * Fixed failing tests * Updated test setup * Updated test * Added suppression * Fixed failing tests * Updated addOnTeardown methods to protected * Added method for clearing the host * Added teardown * Updated model usage * Added a lot of cleanup for memory leak issues when running tests * Added CompatibilitySuppressions.xml * Updated tests * Cleaned up * Adjusted base classes * Updated pipeline * Updated CompatibilitySuppressions.xml * Updated test logging * Fixed reponse * Updated condition to skip tests * Updated tests, not done * Reworked test to expect correct responses with correct setup * Updated tests * More updates to tests * Updated tests * Cleaned up tests * Updated setup * Cleaned up tests to match setup * Cleaned up setup * Removed suppression * Fixed tests * Move order of checks * Fix naming * Formatting * Dispose of host * Keep track of if we're disposed * Compat suppression * Dont dispose * Fix failing tests * removed unused virtual * Updated CompatibilitySuppressions.xml --------- Co-authored-by: Andreas Zerbst <andr317c@live.dk> Co-authored-by: Zeegaan <skrivdetud@gmail.com> Co-authored-by: Nikolaj Geisle <70372949+Zeegaan@users.noreply.github.com> # Conflicts: # tests/Umbraco.Tests.Integration/CompatibilitySuppressions.xml # tests/Umbraco.Tests.Integration/ManagementApi/ManagementApiTest.cs # tests/Umbraco.Tests.Integration/ManagementApi/Policies/AllCultureControllerTests.cs # tests/Umbraco.Tests.Integration/ManagementApi/Policies/CreateDocumentTests.cs # tests/Umbraco.Tests.Integration/ManagementApi/Policies/UpdateDocumentTests.cs # tests/Umbraco.Tests.Integration/ManagementApi/Preview/EndPreviewTests.cs # tests/Umbraco.Tests.Integration/ManagementApi/Preview/EnterPreviewTests.cs # tests/Umbraco.Tests.Integration/TestServerTest/UmbracoTestServerTestBase.cs * Updated test * Updates * Removed unnessecary test --------- Co-authored-by: Nhu Dinh <150406148+nhudinh0309@users.noreply.github.com> Co-authored-by: Zeegaan <skrivdetud@gmail.com> Co-authored-by: Nikolaj Geisle <70372949+Zeegaan@users.noreply.github.com>
2025-10-14 12:04:10 +02:00
private static readonly Dictionary<string, WebApplicationFactory<UmbracoTestServerTestBase>> _factoryCache = new();
protected HttpClient Client { get; private set; }
Auhorization: Cherrypicked integration tests from V15 (#20492) * V15 QA Added the authorization integration tests (#18419) * Added authorization integration tests * Removed unnecessary tests and update tests for preview controller * Updated to use the newest changes from v15/dev and added an override for the AuthenticateClientAsync to use the userGroupKey * Updated CompatibilitySuppressions to include changes from integration tests * Updated pipelines * Skips managementApi tests * Only run necessary tests * Added new schema per fixture to reduce test setup time * Fixed failing tests * Updated test setup * Updated test * Added suppression * Fixed failing tests * Updated addOnTeardown methods to protected * Added method for clearing the host * Added teardown * Updated model usage * Added a lot of cleanup for memory leak issues when running tests * Added CompatibilitySuppressions.xml * Updated tests * Cleaned up * Adjusted base classes * Updated pipeline * Updated CompatibilitySuppressions.xml * Updated test logging * Fixed reponse * Updated condition to skip tests * Updated tests, not done * Reworked test to expect correct responses with correct setup * Updated tests * More updates to tests * Updated tests * Cleaned up tests * Updated setup * Cleaned up tests to match setup * Cleaned up setup * Removed suppression * Fixed tests * Move order of checks * Fix naming * Formatting * Dispose of host * Keep track of if we're disposed * Compat suppression * Dont dispose * Fix failing tests * removed unused virtual * Updated CompatibilitySuppressions.xml --------- Co-authored-by: Andreas Zerbst <andr317c@live.dk> Co-authored-by: Zeegaan <skrivdetud@gmail.com> Co-authored-by: Nikolaj Geisle <70372949+Zeegaan@users.noreply.github.com> # Conflicts: # tests/Umbraco.Tests.Integration/CompatibilitySuppressions.xml # tests/Umbraco.Tests.Integration/ManagementApi/ManagementApiTest.cs # tests/Umbraco.Tests.Integration/ManagementApi/Policies/AllCultureControllerTests.cs # tests/Umbraco.Tests.Integration/ManagementApi/Policies/CreateDocumentTests.cs # tests/Umbraco.Tests.Integration/ManagementApi/Policies/UpdateDocumentTests.cs # tests/Umbraco.Tests.Integration/ManagementApi/Preview/EndPreviewTests.cs # tests/Umbraco.Tests.Integration/ManagementApi/Preview/EnterPreviewTests.cs # tests/Umbraco.Tests.Integration/TestServerTest/UmbracoTestServerTestBase.cs * Updated test * Updates * Removed unnessecary test --------- Co-authored-by: Nhu Dinh <150406148+nhudinh0309@users.noreply.github.com> Co-authored-by: Zeegaan <skrivdetud@gmail.com> Co-authored-by: Nikolaj Geisle <70372949+Zeegaan@users.noreply.github.com>
2025-10-14 12:04:10 +02:00
protected WebApplicationFactory<UmbracoTestServerTestBase> Factory { get; private set; }
protected IServiceProvider Services => Factory?.Services;
V14: Add authorization policies to Management API controllers - p2 (#15211) * Making ProblemDetails details more generic * Adding authorizer that can be replaces for external authz in handlers. Adding handler and requirement for UserBelongsToUserGroupInRequest policy * Adding method to get the GUID from claims * Adding service methods to check user group authz * Porting MustSatisfyRequirementAuthorizationHandler * Adding controllers authz * Fix return status code + produced response type * Moving to folder * Adding DenyLocalLogin policy scaffold * Implement a temp DenyLocalLoginHandler * Introducing a new Fobidden result * Fix comment * Introducing a helper class for authorizers * Changed nullability for GetCurrentUser * Changes from Attempt to Status + FIXME comments * Create a UserGroupAuthorizationStatus to be used in the future * Introduces a new authz status for checking media acess * Introducing a new permission service for media * Adding fixme * Adding more policy configurations * Adding Media policy requirement and handler * Adding media authorizer * Fix order of params * Adding duplicate code comment * Adding authz to media controllers * Migrating more logic from MediaPermissions.cs * Adding more MediaAuthorizationStatus-es * Handling of new authorization status * Fix comment * Adding NotFound case * Adding NewDenyLocalLoginIfConfigured policy && commenting [AllowAnonymous] where the policy is applied since it is already handled * Changed Forbid() to Forbidden() to get the correct status code * Remove policy that is applied on the base controller already * Implement and apply NewUmbracoFeatureEnabled policy * Renaming classes to add Permission in the name * Register permission services * Add FIXME * Introduce new IUserGroupPermissionService and refactor accordingly * Add single overload with default implementation * Adding user permission policy and related * Applying admin policy * Register all new policies * Better wording * Add default implementation for a single overload * Adding remarks to IContentPermissionService.cs * Supporting null as key in ContentPermissionService * Fix namespace * Reverting back to not supporting null as content key, but having dedicated implementation * Adding content authorizer with null values to represent root item * Removing null key support and adding dedicated implementation * Removing remarks * Adding content resource with null support * Removing null support * Adding requirement and status * Adding content authorizer + handlers * Applying policies to content controllers * Update comment * Handling of Authorization Statuses * More authz in controllers * Fix comments * New branch handler * Obsolete old implementation * Adding dedicated policies to root and bin * Adding a branch specific namespace * Bin specific requirement and namespace * Root specific requirement and namespace * Changing to new root policy * Refactoring * Save policies * Fix null check/reference * Add TODO comment * Create media root- and bin-specific policies, handlers, etc. * Apply correct policy in create and update media controllers * Apply root policy to move and sort controllers * Fix wording * Adding UserGroupAuthorizationStatusResult * Remove all AuthorizationStatusResult as we cannot get the specific AuthorizationStatus * Fixing Umbraco feature policy * Fix allow anonymous endpoints - the value returned from DenyLocalLoginHandler wasn't enough, we need to succeed DenyAnonymousAuthorizationRequirement as it is required for some of the endpoints that had the attribute * Apply DenyLocalLoginIfConfigured policy to corresponding re-implementation of PostSetInvitedUserPassword * Fix comment * Renaming performingUser to user and fixing comments * Rename helper method * Fix references * Re-add merge conflict deletion * Adding Backoffice requirement and relevant * Registering * Added a simple policy test * Fixed small test things and clean up * Temp solution * Added one more test and fix another static issue * Fix another merge conflict * Remove BackOfficePermissionRequirement and handler as they might not be necessary * Comment out again [AllowAnonymous] * Remove AuthorizationPolicies.BackOfficeAccessWithoutApproval policy as it might not be necessary * Fix temp implementation * Fix reference to correct handler * Apply authz policy to new publish/unpublish controllers * Fix comments * Removing duplicate ProducesResponseTypes * Added swagger documentation about the 401 and 403 * Added Resources to Media, User and UserGroup * Handle root, recycle bin and branch in the same handler * Handle both parent and target when moving * Check Ids for all sort requests * Xml docs * Clean up * Clean up * Fix build * Cleanup * Remove TODO * Added missing overload * Use yield * Adding some keys to check --------- Co-authored-by: Bjarke Berg <mail@bergmania.dk> Co-authored-by: Andreas Zerbst <andr317c@live.dk>
2023-12-11 08:25:29 +01:00
protected LinkGenerator LinkGenerator => Factory.Services.GetRequiredService<LinkGenerator>();
Auhorization: Cherrypicked integration tests from V15 (#20492) * V15 QA Added the authorization integration tests (#18419) * Added authorization integration tests * Removed unnecessary tests and update tests for preview controller * Updated to use the newest changes from v15/dev and added an override for the AuthenticateClientAsync to use the userGroupKey * Updated CompatibilitySuppressions to include changes from integration tests * Updated pipelines * Skips managementApi tests * Only run necessary tests * Added new schema per fixture to reduce test setup time * Fixed failing tests * Updated test setup * Updated test * Added suppression * Fixed failing tests * Updated addOnTeardown methods to protected * Added method for clearing the host * Added teardown * Updated model usage * Added a lot of cleanup for memory leak issues when running tests * Added CompatibilitySuppressions.xml * Updated tests * Cleaned up * Adjusted base classes * Updated pipeline * Updated CompatibilitySuppressions.xml * Updated test logging * Fixed reponse * Updated condition to skip tests * Updated tests, not done * Reworked test to expect correct responses with correct setup * Updated tests * More updates to tests * Updated tests * Cleaned up tests * Updated setup * Cleaned up tests to match setup * Cleaned up setup * Removed suppression * Fixed tests * Move order of checks * Fix naming * Formatting * Dispose of host * Keep track of if we're disposed * Compat suppression * Dont dispose * Fix failing tests * removed unused virtual * Updated CompatibilitySuppressions.xml --------- Co-authored-by: Andreas Zerbst <andr317c@live.dk> Co-authored-by: Zeegaan <skrivdetud@gmail.com> Co-authored-by: Nikolaj Geisle <70372949+Zeegaan@users.noreply.github.com> # Conflicts: # tests/Umbraco.Tests.Integration/CompatibilitySuppressions.xml # tests/Umbraco.Tests.Integration/ManagementApi/ManagementApiTest.cs # tests/Umbraco.Tests.Integration/ManagementApi/Policies/AllCultureControllerTests.cs # tests/Umbraco.Tests.Integration/ManagementApi/Policies/CreateDocumentTests.cs # tests/Umbraco.Tests.Integration/ManagementApi/Policies/UpdateDocumentTests.cs # tests/Umbraco.Tests.Integration/ManagementApi/Preview/EndPreviewTests.cs # tests/Umbraco.Tests.Integration/ManagementApi/Preview/EnterPreviewTests.cs # tests/Umbraco.Tests.Integration/TestServerTest/UmbracoTestServerTestBase.cs * Updated test * Updates * Removed unnessecary test --------- Co-authored-by: Nhu Dinh <150406148+nhudinh0309@users.noreply.github.com> Co-authored-by: Zeegaan <skrivdetud@gmail.com> Co-authored-by: Nikolaj Geisle <70372949+Zeegaan@users.noreply.github.com>
2025-10-14 12:04:10 +02:00
protected void CustomMvcSetup(IMvcBuilder mvcBuilder)
{
}
protected virtual void ConfigureTestServices(IServiceCollection services)
{
}
/// <summary>
/// Hook for altering UmbracoBuilder setup
/// </summary>
/// <remarks>
/// Can also be used for registering test doubles.
/// </remarks>
protected virtual void CustomTestSetup(IUmbracoBuilder builder)
{
}
V14: Add authorization policies to Management API controllers - p2 (#15211) * Making ProblemDetails details more generic * Adding authorizer that can be replaces for external authz in handlers. Adding handler and requirement for UserBelongsToUserGroupInRequest policy * Adding method to get the GUID from claims * Adding service methods to check user group authz * Porting MustSatisfyRequirementAuthorizationHandler * Adding controllers authz * Fix return status code + produced response type * Moving to folder * Adding DenyLocalLogin policy scaffold * Implement a temp DenyLocalLoginHandler * Introducing a new Fobidden result * Fix comment * Introducing a helper class for authorizers * Changed nullability for GetCurrentUser * Changes from Attempt to Status + FIXME comments * Create a UserGroupAuthorizationStatus to be used in the future * Introduces a new authz status for checking media acess * Introducing a new permission service for media * Adding fixme * Adding more policy configurations * Adding Media policy requirement and handler * Adding media authorizer * Fix order of params * Adding duplicate code comment * Adding authz to media controllers * Migrating more logic from MediaPermissions.cs * Adding more MediaAuthorizationStatus-es * Handling of new authorization status * Fix comment * Adding NotFound case * Adding NewDenyLocalLoginIfConfigured policy && commenting [AllowAnonymous] where the policy is applied since it is already handled * Changed Forbid() to Forbidden() to get the correct status code * Remove policy that is applied on the base controller already * Implement and apply NewUmbracoFeatureEnabled policy * Renaming classes to add Permission in the name * Register permission services * Add FIXME * Introduce new IUserGroupPermissionService and refactor accordingly * Add single overload with default implementation * Adding user permission policy and related * Applying admin policy * Register all new policies * Better wording * Add default implementation for a single overload * Adding remarks to IContentPermissionService.cs * Supporting null as key in ContentPermissionService * Fix namespace * Reverting back to not supporting null as content key, but having dedicated implementation * Adding content authorizer with null values to represent root item * Removing null key support and adding dedicated implementation * Removing remarks * Adding content resource with null support * Removing null support * Adding requirement and status * Adding content authorizer + handlers * Applying policies to content controllers * Update comment * Handling of Authorization Statuses * More authz in controllers * Fix comments * New branch handler * Obsolete old implementation * Adding dedicated policies to root and bin * Adding a branch specific namespace * Bin specific requirement and namespace * Root specific requirement and namespace * Changing to new root policy * Refactoring * Save policies * Fix null check/reference * Add TODO comment * Create media root- and bin-specific policies, handlers, etc. * Apply correct policy in create and update media controllers * Apply root policy to move and sort controllers * Fix wording * Adding UserGroupAuthorizationStatusResult * Remove all AuthorizationStatusResult as we cannot get the specific AuthorizationStatus * Fixing Umbraco feature policy * Fix allow anonymous endpoints - the value returned from DenyLocalLoginHandler wasn't enough, we need to succeed DenyAnonymousAuthorizationRequirement as it is required for some of the endpoints that had the attribute * Apply DenyLocalLoginIfConfigured policy to corresponding re-implementation of PostSetInvitedUserPassword * Fix comment * Renaming performingUser to user and fixing comments * Rename helper method * Fix references * Re-add merge conflict deletion * Adding Backoffice requirement and relevant * Registering * Added a simple policy test * Fixed small test things and clean up * Temp solution * Added one more test and fix another static issue * Fix another merge conflict * Remove BackOfficePermissionRequirement and handler as they might not be necessary * Comment out again [AllowAnonymous] * Remove AuthorizationPolicies.BackOfficeAccessWithoutApproval policy as it might not be necessary * Fix temp implementation * Fix reference to correct handler * Apply authz policy to new publish/unpublish controllers * Fix comments * Removing duplicate ProducesResponseTypes * Added swagger documentation about the 401 and 403 * Added Resources to Media, User and UserGroup * Handle root, recycle bin and branch in the same handler * Handle both parent and target when moving * Check Ids for all sort requests * Xml docs * Clean up * Clean up * Fix build * Cleanup * Remove TODO * Added missing overload * Use yield * Adding some keys to check --------- Co-authored-by: Bjarke Berg <mail@bergmania.dk> Co-authored-by: Andreas Zerbst <andr317c@live.dk>
2023-12-11 08:25:29 +01:00
protected virtual void CustomTestAuthSetup(IServiceCollection services)
{
// Add a test auth scheme with a test auth handler to authn and assign the user
services.AddAuthentication(TestAuthHandler.TestAuthenticationScheme)
Auhorization: Cherrypicked integration tests from V15 (#20492) * V15 QA Added the authorization integration tests (#18419) * Added authorization integration tests * Removed unnecessary tests and update tests for preview controller * Updated to use the newest changes from v15/dev and added an override for the AuthenticateClientAsync to use the userGroupKey * Updated CompatibilitySuppressions to include changes from integration tests * Updated pipelines * Skips managementApi tests * Only run necessary tests * Added new schema per fixture to reduce test setup time * Fixed failing tests * Updated test setup * Updated test * Added suppression * Fixed failing tests * Updated addOnTeardown methods to protected * Added method for clearing the host * Added teardown * Updated model usage * Added a lot of cleanup for memory leak issues when running tests * Added CompatibilitySuppressions.xml * Updated tests * Cleaned up * Adjusted base classes * Updated pipeline * Updated CompatibilitySuppressions.xml * Updated test logging * Fixed reponse * Updated condition to skip tests * Updated tests, not done * Reworked test to expect correct responses with correct setup * Updated tests * More updates to tests * Updated tests * Cleaned up tests * Updated setup * Cleaned up tests to match setup * Cleaned up setup * Removed suppression * Fixed tests * Move order of checks * Fix naming * Formatting * Dispose of host * Keep track of if we're disposed * Compat suppression * Dont dispose * Fix failing tests * removed unused virtual * Updated CompatibilitySuppressions.xml --------- Co-authored-by: Andreas Zerbst <andr317c@live.dk> Co-authored-by: Zeegaan <skrivdetud@gmail.com> Co-authored-by: Nikolaj Geisle <70372949+Zeegaan@users.noreply.github.com> # Conflicts: # tests/Umbraco.Tests.Integration/CompatibilitySuppressions.xml # tests/Umbraco.Tests.Integration/ManagementApi/ManagementApiTest.cs # tests/Umbraco.Tests.Integration/ManagementApi/Policies/AllCultureControllerTests.cs # tests/Umbraco.Tests.Integration/ManagementApi/Policies/CreateDocumentTests.cs # tests/Umbraco.Tests.Integration/ManagementApi/Policies/UpdateDocumentTests.cs # tests/Umbraco.Tests.Integration/ManagementApi/Preview/EndPreviewTests.cs # tests/Umbraco.Tests.Integration/ManagementApi/Preview/EnterPreviewTests.cs # tests/Umbraco.Tests.Integration/TestServerTest/UmbracoTestServerTestBase.cs * Updated test * Updates * Removed unnessecary test --------- Co-authored-by: Nhu Dinh <150406148+nhudinh0309@users.noreply.github.com> Co-authored-by: Zeegaan <skrivdetud@gmail.com> Co-authored-by: Nikolaj Geisle <70372949+Zeegaan@users.noreply.github.com>
2025-10-14 12:04:10 +02:00
.AddScheme<AuthenticationSchemeOptions, TestAuthHandler>(TestAuthHandler.TestAuthenticationScheme,
options => { });
V14: Add authorization policies to Management API controllers - p2 (#15211) * Making ProblemDetails details more generic * Adding authorizer that can be replaces for external authz in handlers. Adding handler and requirement for UserBelongsToUserGroupInRequest policy * Adding method to get the GUID from claims * Adding service methods to check user group authz * Porting MustSatisfyRequirementAuthorizationHandler * Adding controllers authz * Fix return status code + produced response type * Moving to folder * Adding DenyLocalLogin policy scaffold * Implement a temp DenyLocalLoginHandler * Introducing a new Fobidden result * Fix comment * Introducing a helper class for authorizers * Changed nullability for GetCurrentUser * Changes from Attempt to Status + FIXME comments * Create a UserGroupAuthorizationStatus to be used in the future * Introduces a new authz status for checking media acess * Introducing a new permission service for media * Adding fixme * Adding more policy configurations * Adding Media policy requirement and handler * Adding media authorizer * Fix order of params * Adding duplicate code comment * Adding authz to media controllers * Migrating more logic from MediaPermissions.cs * Adding more MediaAuthorizationStatus-es * Handling of new authorization status * Fix comment * Adding NotFound case * Adding NewDenyLocalLoginIfConfigured policy && commenting [AllowAnonymous] where the policy is applied since it is already handled * Changed Forbid() to Forbidden() to get the correct status code * Remove policy that is applied on the base controller already * Implement and apply NewUmbracoFeatureEnabled policy * Renaming classes to add Permission in the name * Register permission services * Add FIXME * Introduce new IUserGroupPermissionService and refactor accordingly * Add single overload with default implementation * Adding user permission policy and related * Applying admin policy * Register all new policies * Better wording * Add default implementation for a single overload * Adding remarks to IContentPermissionService.cs * Supporting null as key in ContentPermissionService * Fix namespace * Reverting back to not supporting null as content key, but having dedicated implementation * Adding content authorizer with null values to represent root item * Removing null key support and adding dedicated implementation * Removing remarks * Adding content resource with null support * Removing null support * Adding requirement and status * Adding content authorizer + handlers * Applying policies to content controllers * Update comment * Handling of Authorization Statuses * More authz in controllers * Fix comments * New branch handler * Obsolete old implementation * Adding dedicated policies to root and bin * Adding a branch specific namespace * Bin specific requirement and namespace * Root specific requirement and namespace * Changing to new root policy * Refactoring * Save policies * Fix null check/reference * Add TODO comment * Create media root- and bin-specific policies, handlers, etc. * Apply correct policy in create and update media controllers * Apply root policy to move and sort controllers * Fix wording * Adding UserGroupAuthorizationStatusResult * Remove all AuthorizationStatusResult as we cannot get the specific AuthorizationStatus * Fixing Umbraco feature policy * Fix allow anonymous endpoints - the value returned from DenyLocalLoginHandler wasn't enough, we need to succeed DenyAnonymousAuthorizationRequirement as it is required for some of the endpoints that had the attribute * Apply DenyLocalLoginIfConfigured policy to corresponding re-implementation of PostSetInvitedUserPassword * Fix comment * Renaming performingUser to user and fixing comments * Rename helper method * Fix references * Re-add merge conflict deletion * Adding Backoffice requirement and relevant * Registering * Added a simple policy test * Fixed small test things and clean up * Temp solution * Added one more test and fix another static issue * Fix another merge conflict * Remove BackOfficePermissionRequirement and handler as they might not be necessary * Comment out again [AllowAnonymous] * Remove AuthorizationPolicies.BackOfficeAccessWithoutApproval policy as it might not be necessary * Fix temp implementation * Fix reference to correct handler * Apply authz policy to new publish/unpublish controllers * Fix comments * Removing duplicate ProducesResponseTypes * Added swagger documentation about the 401 and 403 * Added Resources to Media, User and UserGroup * Handle root, recycle bin and branch in the same handler * Handle both parent and target when moving * Check Ids for all sort requests * Xml docs * Clean up * Clean up * Fix build * Cleanup * Remove TODO * Added missing overload * Use yield * Adding some keys to check --------- Co-authored-by: Bjarke Berg <mail@bergmania.dk> Co-authored-by: Andreas Zerbst <andr317c@live.dk>
2023-12-11 08:25:29 +01:00
}
[SetUp]
Auhorization: Cherrypicked integration tests from V15 (#20492) * V15 QA Added the authorization integration tests (#18419) * Added authorization integration tests * Removed unnecessary tests and update tests for preview controller * Updated to use the newest changes from v15/dev and added an override for the AuthenticateClientAsync to use the userGroupKey * Updated CompatibilitySuppressions to include changes from integration tests * Updated pipelines * Skips managementApi tests * Only run necessary tests * Added new schema per fixture to reduce test setup time * Fixed failing tests * Updated test setup * Updated test * Added suppression * Fixed failing tests * Updated addOnTeardown methods to protected * Added method for clearing the host * Added teardown * Updated model usage * Added a lot of cleanup for memory leak issues when running tests * Added CompatibilitySuppressions.xml * Updated tests * Cleaned up * Adjusted base classes * Updated pipeline * Updated CompatibilitySuppressions.xml * Updated test logging * Fixed reponse * Updated condition to skip tests * Updated tests, not done * Reworked test to expect correct responses with correct setup * Updated tests * More updates to tests * Updated tests * Cleaned up tests * Updated setup * Cleaned up tests to match setup * Cleaned up setup * Removed suppression * Fixed tests * Move order of checks * Fix naming * Formatting * Dispose of host * Keep track of if we're disposed * Compat suppression * Dont dispose * Fix failing tests * removed unused virtual * Updated CompatibilitySuppressions.xml --------- Co-authored-by: Andreas Zerbst <andr317c@live.dk> Co-authored-by: Zeegaan <skrivdetud@gmail.com> Co-authored-by: Nikolaj Geisle <70372949+Zeegaan@users.noreply.github.com> # Conflicts: # tests/Umbraco.Tests.Integration/CompatibilitySuppressions.xml # tests/Umbraco.Tests.Integration/ManagementApi/ManagementApiTest.cs # tests/Umbraco.Tests.Integration/ManagementApi/Policies/AllCultureControllerTests.cs # tests/Umbraco.Tests.Integration/ManagementApi/Policies/CreateDocumentTests.cs # tests/Umbraco.Tests.Integration/ManagementApi/Policies/UpdateDocumentTests.cs # tests/Umbraco.Tests.Integration/ManagementApi/Preview/EndPreviewTests.cs # tests/Umbraco.Tests.Integration/ManagementApi/Preview/EnterPreviewTests.cs # tests/Umbraco.Tests.Integration/TestServerTest/UmbracoTestServerTestBase.cs * Updated test * Updates * Removed unnessecary test --------- Co-authored-by: Nhu Dinh <150406148+nhudinh0309@users.noreply.github.com> Co-authored-by: Zeegaan <skrivdetud@gmail.com> Co-authored-by: Nikolaj Geisle <70372949+Zeegaan@users.noreply.github.com>
2025-10-14 12:04:10 +02:00
public virtual void Setup()
{
// Don't cache factory if using NewSchemaPerTest
if (TestOptions.Database == UmbracoTestOptions.Database.NewSchemaPerTest ||
TestOptions.Database == UmbracoTestOptions.Database.NewEmptyPerTest)
{
// Create a new factory for each test when using per-test database
Factory = CreateNewFactory();
}
else
{
// Use cached factory for per-fixture database options
var cacheKey = $"{TestOptions.Database}_{TestOptions.Boot}";
if (!_factoryCache.TryGetValue(cacheKey, out var cachedFactory))
{
cachedFactory = CreateNewFactory();
_factoryCache[cacheKey] = cachedFactory;
}
Factory = cachedFactory;
}
Client = Factory.CreateClient(new WebApplicationFactoryClientOptions
{
AllowAutoRedirect = false, BaseAddress = new Uri("https://localhost/", UriKind.Absolute),
});
}
private WebApplicationFactory<UmbracoTestServerTestBase> CreateNewFactory()
{
/*
* It's worth noting that our usage of WebApplicationFactory is non-standard,
* the intent is that your Startup.ConfigureServices is called just like
* when the app starts up, then replacements are registered in this class with
* builder.ConfigureServices (builder.ConfigureTestServices has hung around from before the
* generic host switchover).
*
* This is currently a pain to refactor towards due to UmbracoBuilder+TypeFinder+TypeLoader setup but
* we should get there one day.
*
* However we need to separate the testing framework we provide for downstream projects from our own tests.
* We cannot use the Umbraco.Web.UI startup yet as that is not available downstream.
*
* See https://docs.microsoft.com/en-us/aspnet/core/test/integration-tests
*/
Auhorization: Cherrypicked integration tests from V15 (#20492) * V15 QA Added the authorization integration tests (#18419) * Added authorization integration tests * Removed unnecessary tests and update tests for preview controller * Updated to use the newest changes from v15/dev and added an override for the AuthenticateClientAsync to use the userGroupKey * Updated CompatibilitySuppressions to include changes from integration tests * Updated pipelines * Skips managementApi tests * Only run necessary tests * Added new schema per fixture to reduce test setup time * Fixed failing tests * Updated test setup * Updated test * Added suppression * Fixed failing tests * Updated addOnTeardown methods to protected * Added method for clearing the host * Added teardown * Updated model usage * Added a lot of cleanup for memory leak issues when running tests * Added CompatibilitySuppressions.xml * Updated tests * Cleaned up * Adjusted base classes * Updated pipeline * Updated CompatibilitySuppressions.xml * Updated test logging * Fixed reponse * Updated condition to skip tests * Updated tests, not done * Reworked test to expect correct responses with correct setup * Updated tests * More updates to tests * Updated tests * Cleaned up tests * Updated setup * Cleaned up tests to match setup * Cleaned up setup * Removed suppression * Fixed tests * Move order of checks * Fix naming * Formatting * Dispose of host * Keep track of if we're disposed * Compat suppression * Dont dispose * Fix failing tests * removed unused virtual * Updated CompatibilitySuppressions.xml --------- Co-authored-by: Andreas Zerbst <andr317c@live.dk> Co-authored-by: Zeegaan <skrivdetud@gmail.com> Co-authored-by: Nikolaj Geisle <70372949+Zeegaan@users.noreply.github.com> # Conflicts: # tests/Umbraco.Tests.Integration/CompatibilitySuppressions.xml # tests/Umbraco.Tests.Integration/ManagementApi/ManagementApiTest.cs # tests/Umbraco.Tests.Integration/ManagementApi/Policies/AllCultureControllerTests.cs # tests/Umbraco.Tests.Integration/ManagementApi/Policies/CreateDocumentTests.cs # tests/Umbraco.Tests.Integration/ManagementApi/Policies/UpdateDocumentTests.cs # tests/Umbraco.Tests.Integration/ManagementApi/Preview/EndPreviewTests.cs # tests/Umbraco.Tests.Integration/ManagementApi/Preview/EnterPreviewTests.cs # tests/Umbraco.Tests.Integration/TestServerTest/UmbracoTestServerTestBase.cs * Updated test * Updates * Removed unnessecary test --------- Co-authored-by: Nhu Dinh <150406148+nhudinh0309@users.noreply.github.com> Co-authored-by: Zeegaan <skrivdetud@gmail.com> Co-authored-by: Nikolaj Geisle <70372949+Zeegaan@users.noreply.github.com>
2025-10-14 12:04:10 +02:00
return new UmbracoWebApplicationFactory<UmbracoTestServerTestBase>(CreateHostBuilder)
.WithWebHostBuilder(builder =>
{
builder.UseContentRoot(Assembly.GetExecutingAssembly().GetRootDirectorySafe());
builder.ConfigureTestServices(services =>
{
services.AddSingleton<IWebProfilerRepository, TestWebProfilerRepository>();
CustomTestAuthSetup(services);
});
});
}
Auhorization: Cherrypicked integration tests from V15 (#20492) * V15 QA Added the authorization integration tests (#18419) * Added authorization integration tests * Removed unnecessary tests and update tests for preview controller * Updated to use the newest changes from v15/dev and added an override for the AuthenticateClientAsync to use the userGroupKey * Updated CompatibilitySuppressions to include changes from integration tests * Updated pipelines * Skips managementApi tests * Only run necessary tests * Added new schema per fixture to reduce test setup time * Fixed failing tests * Updated test setup * Updated test * Added suppression * Fixed failing tests * Updated addOnTeardown methods to protected * Added method for clearing the host * Added teardown * Updated model usage * Added a lot of cleanup for memory leak issues when running tests * Added CompatibilitySuppressions.xml * Updated tests * Cleaned up * Adjusted base classes * Updated pipeline * Updated CompatibilitySuppressions.xml * Updated test logging * Fixed reponse * Updated condition to skip tests * Updated tests, not done * Reworked test to expect correct responses with correct setup * Updated tests * More updates to tests * Updated tests * Cleaned up tests * Updated setup * Cleaned up tests to match setup * Cleaned up setup * Removed suppression * Fixed tests * Move order of checks * Fix naming * Formatting * Dispose of host * Keep track of if we're disposed * Compat suppression * Dont dispose * Fix failing tests * removed unused virtual * Updated CompatibilitySuppressions.xml --------- Co-authored-by: Andreas Zerbst <andr317c@live.dk> Co-authored-by: Zeegaan <skrivdetud@gmail.com> Co-authored-by: Nikolaj Geisle <70372949+Zeegaan@users.noreply.github.com> # Conflicts: # tests/Umbraco.Tests.Integration/CompatibilitySuppressions.xml # tests/Umbraco.Tests.Integration/ManagementApi/ManagementApiTest.cs # tests/Umbraco.Tests.Integration/ManagementApi/Policies/AllCultureControllerTests.cs # tests/Umbraco.Tests.Integration/ManagementApi/Policies/CreateDocumentTests.cs # tests/Umbraco.Tests.Integration/ManagementApi/Policies/UpdateDocumentTests.cs # tests/Umbraco.Tests.Integration/ManagementApi/Preview/EndPreviewTests.cs # tests/Umbraco.Tests.Integration/ManagementApi/Preview/EnterPreviewTests.cs # tests/Umbraco.Tests.Integration/TestServerTest/UmbracoTestServerTestBase.cs * Updated test * Updates * Removed unnessecary test --------- Co-authored-by: Nhu Dinh <150406148+nhudinh0309@users.noreply.github.com> Co-authored-by: Zeegaan <skrivdetud@gmail.com> Co-authored-by: Nikolaj Geisle <70372949+Zeegaan@users.noreply.github.com>
2025-10-14 12:04:10 +02:00
[TearDown]
public void TearDownClient()
{
Client?.Dispose();
V14: Add authorization policies to Management API controllers - p2 (#15211) * Making ProblemDetails details more generic * Adding authorizer that can be replaces for external authz in handlers. Adding handler and requirement for UserBelongsToUserGroupInRequest policy * Adding method to get the GUID from claims * Adding service methods to check user group authz * Porting MustSatisfyRequirementAuthorizationHandler * Adding controllers authz * Fix return status code + produced response type * Moving to folder * Adding DenyLocalLogin policy scaffold * Implement a temp DenyLocalLoginHandler * Introducing a new Fobidden result * Fix comment * Introducing a helper class for authorizers * Changed nullability for GetCurrentUser * Changes from Attempt to Status + FIXME comments * Create a UserGroupAuthorizationStatus to be used in the future * Introduces a new authz status for checking media acess * Introducing a new permission service for media * Adding fixme * Adding more policy configurations * Adding Media policy requirement and handler * Adding media authorizer * Fix order of params * Adding duplicate code comment * Adding authz to media controllers * Migrating more logic from MediaPermissions.cs * Adding more MediaAuthorizationStatus-es * Handling of new authorization status * Fix comment * Adding NotFound case * Adding NewDenyLocalLoginIfConfigured policy && commenting [AllowAnonymous] where the policy is applied since it is already handled * Changed Forbid() to Forbidden() to get the correct status code * Remove policy that is applied on the base controller already * Implement and apply NewUmbracoFeatureEnabled policy * Renaming classes to add Permission in the name * Register permission services * Add FIXME * Introduce new IUserGroupPermissionService and refactor accordingly * Add single overload with default implementation * Adding user permission policy and related * Applying admin policy * Register all new policies * Better wording * Add default implementation for a single overload * Adding remarks to IContentPermissionService.cs * Supporting null as key in ContentPermissionService * Fix namespace * Reverting back to not supporting null as content key, but having dedicated implementation * Adding content authorizer with null values to represent root item * Removing null key support and adding dedicated implementation * Removing remarks * Adding content resource with null support * Removing null support * Adding requirement and status * Adding content authorizer + handlers * Applying policies to content controllers * Update comment * Handling of Authorization Statuses * More authz in controllers * Fix comments * New branch handler * Obsolete old implementation * Adding dedicated policies to root and bin * Adding a branch specific namespace * Bin specific requirement and namespace * Root specific requirement and namespace * Changing to new root policy * Refactoring * Save policies * Fix null check/reference * Add TODO comment * Create media root- and bin-specific policies, handlers, etc. * Apply correct policy in create and update media controllers * Apply root policy to move and sort controllers * Fix wording * Adding UserGroupAuthorizationStatusResult * Remove all AuthorizationStatusResult as we cannot get the specific AuthorizationStatus * Fixing Umbraco feature policy * Fix allow anonymous endpoints - the value returned from DenyLocalLoginHandler wasn't enough, we need to succeed DenyAnonymousAuthorizationRequirement as it is required for some of the endpoints that had the attribute * Apply DenyLocalLoginIfConfigured policy to corresponding re-implementation of PostSetInvitedUserPassword * Fix comment * Renaming performingUser to user and fixing comments * Rename helper method * Fix references * Re-add merge conflict deletion * Adding Backoffice requirement and relevant * Registering * Added a simple policy test * Fixed small test things and clean up * Temp solution * Added one more test and fix another static issue * Fix another merge conflict * Remove BackOfficePermissionRequirement and handler as they might not be necessary * Comment out again [AllowAnonymous] * Remove AuthorizationPolicies.BackOfficeAccessWithoutApproval policy as it might not be necessary * Fix temp implementation * Fix reference to correct handler * Apply authz policy to new publish/unpublish controllers * Fix comments * Removing duplicate ProducesResponseTypes * Added swagger documentation about the 401 and 403 * Added Resources to Media, User and UserGroup * Handle root, recycle bin and branch in the same handler * Handle both parent and target when moving * Check Ids for all sort requests * Xml docs * Clean up * Clean up * Fix build * Cleanup * Remove TODO * Added missing overload * Use yield * Adding some keys to check --------- Co-authored-by: Bjarke Berg <mail@bergmania.dk> Co-authored-by: Andreas Zerbst <andr317c@live.dk>
2023-12-11 08:25:29 +01:00
Auhorization: Cherrypicked integration tests from V15 (#20492) * V15 QA Added the authorization integration tests (#18419) * Added authorization integration tests * Removed unnecessary tests and update tests for preview controller * Updated to use the newest changes from v15/dev and added an override for the AuthenticateClientAsync to use the userGroupKey * Updated CompatibilitySuppressions to include changes from integration tests * Updated pipelines * Skips managementApi tests * Only run necessary tests * Added new schema per fixture to reduce test setup time * Fixed failing tests * Updated test setup * Updated test * Added suppression * Fixed failing tests * Updated addOnTeardown methods to protected * Added method for clearing the host * Added teardown * Updated model usage * Added a lot of cleanup for memory leak issues when running tests * Added CompatibilitySuppressions.xml * Updated tests * Cleaned up * Adjusted base classes * Updated pipeline * Updated CompatibilitySuppressions.xml * Updated test logging * Fixed reponse * Updated condition to skip tests * Updated tests, not done * Reworked test to expect correct responses with correct setup * Updated tests * More updates to tests * Updated tests * Cleaned up tests * Updated setup * Cleaned up tests to match setup * Cleaned up setup * Removed suppression * Fixed tests * Move order of checks * Fix naming * Formatting * Dispose of host * Keep track of if we're disposed * Compat suppression * Dont dispose * Fix failing tests * removed unused virtual * Updated CompatibilitySuppressions.xml --------- Co-authored-by: Andreas Zerbst <andr317c@live.dk> Co-authored-by: Zeegaan <skrivdetud@gmail.com> Co-authored-by: Nikolaj Geisle <70372949+Zeegaan@users.noreply.github.com> # Conflicts: # tests/Umbraco.Tests.Integration/CompatibilitySuppressions.xml # tests/Umbraco.Tests.Integration/ManagementApi/ManagementApiTest.cs # tests/Umbraco.Tests.Integration/ManagementApi/Policies/AllCultureControllerTests.cs # tests/Umbraco.Tests.Integration/ManagementApi/Policies/CreateDocumentTests.cs # tests/Umbraco.Tests.Integration/ManagementApi/Policies/UpdateDocumentTests.cs # tests/Umbraco.Tests.Integration/ManagementApi/Preview/EndPreviewTests.cs # tests/Umbraco.Tests.Integration/ManagementApi/Preview/EnterPreviewTests.cs # tests/Umbraco.Tests.Integration/TestServerTest/UmbracoTestServerTestBase.cs * Updated test * Updates * Removed unnessecary test --------- Co-authored-by: Nhu Dinh <150406148+nhudinh0309@users.noreply.github.com> Co-authored-by: Zeegaan <skrivdetud@gmail.com> Co-authored-by: Nikolaj Geisle <70372949+Zeegaan@users.noreply.github.com>
2025-10-14 12:04:10 +02:00
// Dispose the factory if using per-test database
if (TestOptions.Database == UmbracoTestOptions.Database.NewSchemaPerTest ||
TestOptions.Database == UmbracoTestOptions.Database.NewEmptyPerTest)
{
Auhorization: Cherrypicked integration tests from V15 (#20492) * V15 QA Added the authorization integration tests (#18419) * Added authorization integration tests * Removed unnecessary tests and update tests for preview controller * Updated to use the newest changes from v15/dev and added an override for the AuthenticateClientAsync to use the userGroupKey * Updated CompatibilitySuppressions to include changes from integration tests * Updated pipelines * Skips managementApi tests * Only run necessary tests * Added new schema per fixture to reduce test setup time * Fixed failing tests * Updated test setup * Updated test * Added suppression * Fixed failing tests * Updated addOnTeardown methods to protected * Added method for clearing the host * Added teardown * Updated model usage * Added a lot of cleanup for memory leak issues when running tests * Added CompatibilitySuppressions.xml * Updated tests * Cleaned up * Adjusted base classes * Updated pipeline * Updated CompatibilitySuppressions.xml * Updated test logging * Fixed reponse * Updated condition to skip tests * Updated tests, not done * Reworked test to expect correct responses with correct setup * Updated tests * More updates to tests * Updated tests * Cleaned up tests * Updated setup * Cleaned up tests to match setup * Cleaned up setup * Removed suppression * Fixed tests * Move order of checks * Fix naming * Formatting * Dispose of host * Keep track of if we're disposed * Compat suppression * Dont dispose * Fix failing tests * removed unused virtual * Updated CompatibilitySuppressions.xml --------- Co-authored-by: Andreas Zerbst <andr317c@live.dk> Co-authored-by: Zeegaan <skrivdetud@gmail.com> Co-authored-by: Nikolaj Geisle <70372949+Zeegaan@users.noreply.github.com> # Conflicts: # tests/Umbraco.Tests.Integration/CompatibilitySuppressions.xml # tests/Umbraco.Tests.Integration/ManagementApi/ManagementApiTest.cs # tests/Umbraco.Tests.Integration/ManagementApi/Policies/AllCultureControllerTests.cs # tests/Umbraco.Tests.Integration/ManagementApi/Policies/CreateDocumentTests.cs # tests/Umbraco.Tests.Integration/ManagementApi/Policies/UpdateDocumentTests.cs # tests/Umbraco.Tests.Integration/ManagementApi/Preview/EndPreviewTests.cs # tests/Umbraco.Tests.Integration/ManagementApi/Preview/EnterPreviewTests.cs # tests/Umbraco.Tests.Integration/TestServerTest/UmbracoTestServerTestBase.cs * Updated test * Updates * Removed unnessecary test --------- Co-authored-by: Nhu Dinh <150406148+nhudinh0309@users.noreply.github.com> Co-authored-by: Zeegaan <skrivdetud@gmail.com> Co-authored-by: Nikolaj Geisle <70372949+Zeegaan@users.noreply.github.com>
2025-10-14 12:04:10 +02:00
Factory?.Dispose();
Factory = null;
}
}
Auhorization: Cherrypicked integration tests from V15 (#20492) * V15 QA Added the authorization integration tests (#18419) * Added authorization integration tests * Removed unnecessary tests and update tests for preview controller * Updated to use the newest changes from v15/dev and added an override for the AuthenticateClientAsync to use the userGroupKey * Updated CompatibilitySuppressions to include changes from integration tests * Updated pipelines * Skips managementApi tests * Only run necessary tests * Added new schema per fixture to reduce test setup time * Fixed failing tests * Updated test setup * Updated test * Added suppression * Fixed failing tests * Updated addOnTeardown methods to protected * Added method for clearing the host * Added teardown * Updated model usage * Added a lot of cleanup for memory leak issues when running tests * Added CompatibilitySuppressions.xml * Updated tests * Cleaned up * Adjusted base classes * Updated pipeline * Updated CompatibilitySuppressions.xml * Updated test logging * Fixed reponse * Updated condition to skip tests * Updated tests, not done * Reworked test to expect correct responses with correct setup * Updated tests * More updates to tests * Updated tests * Cleaned up tests * Updated setup * Cleaned up tests to match setup * Cleaned up setup * Removed suppression * Fixed tests * Move order of checks * Fix naming * Formatting * Dispose of host * Keep track of if we're disposed * Compat suppression * Dont dispose * Fix failing tests * removed unused virtual * Updated CompatibilitySuppressions.xml --------- Co-authored-by: Andreas Zerbst <andr317c@live.dk> Co-authored-by: Zeegaan <skrivdetud@gmail.com> Co-authored-by: Nikolaj Geisle <70372949+Zeegaan@users.noreply.github.com> # Conflicts: # tests/Umbraco.Tests.Integration/CompatibilitySuppressions.xml # tests/Umbraco.Tests.Integration/ManagementApi/ManagementApiTest.cs # tests/Umbraco.Tests.Integration/ManagementApi/Policies/AllCultureControllerTests.cs # tests/Umbraco.Tests.Integration/ManagementApi/Policies/CreateDocumentTests.cs # tests/Umbraco.Tests.Integration/ManagementApi/Policies/UpdateDocumentTests.cs # tests/Umbraco.Tests.Integration/ManagementApi/Preview/EndPreviewTests.cs # tests/Umbraco.Tests.Integration/ManagementApi/Preview/EnterPreviewTests.cs # tests/Umbraco.Tests.Integration/TestServerTest/UmbracoTestServerTestBase.cs * Updated test * Updates * Removed unnessecary test --------- Co-authored-by: Nhu Dinh <150406148+nhudinh0309@users.noreply.github.com> Co-authored-by: Zeegaan <skrivdetud@gmail.com> Co-authored-by: Nikolaj Geisle <70372949+Zeegaan@users.noreply.github.com>
2025-10-14 12:04:10 +02:00
[OneTimeTearDown]
public static async Task CleanupFactories()
{
foreach (var factory in _factoryCache.Values)
{
Auhorization: Cherrypicked integration tests from V15 (#20492) * V15 QA Added the authorization integration tests (#18419) * Added authorization integration tests * Removed unnecessary tests and update tests for preview controller * Updated to use the newest changes from v15/dev and added an override for the AuthenticateClientAsync to use the userGroupKey * Updated CompatibilitySuppressions to include changes from integration tests * Updated pipelines * Skips managementApi tests * Only run necessary tests * Added new schema per fixture to reduce test setup time * Fixed failing tests * Updated test setup * Updated test * Added suppression * Fixed failing tests * Updated addOnTeardown methods to protected * Added method for clearing the host * Added teardown * Updated model usage * Added a lot of cleanup for memory leak issues when running tests * Added CompatibilitySuppressions.xml * Updated tests * Cleaned up * Adjusted base classes * Updated pipeline * Updated CompatibilitySuppressions.xml * Updated test logging * Fixed reponse * Updated condition to skip tests * Updated tests, not done * Reworked test to expect correct responses with correct setup * Updated tests * More updates to tests * Updated tests * Cleaned up tests * Updated setup * Cleaned up tests to match setup * Cleaned up setup * Removed suppression * Fixed tests * Move order of checks * Fix naming * Formatting * Dispose of host * Keep track of if we're disposed * Compat suppression * Dont dispose * Fix failing tests * removed unused virtual * Updated CompatibilitySuppressions.xml --------- Co-authored-by: Andreas Zerbst <andr317c@live.dk> Co-authored-by: Zeegaan <skrivdetud@gmail.com> Co-authored-by: Nikolaj Geisle <70372949+Zeegaan@users.noreply.github.com> # Conflicts: # tests/Umbraco.Tests.Integration/CompatibilitySuppressions.xml # tests/Umbraco.Tests.Integration/ManagementApi/ManagementApiTest.cs # tests/Umbraco.Tests.Integration/ManagementApi/Policies/AllCultureControllerTests.cs # tests/Umbraco.Tests.Integration/ManagementApi/Policies/CreateDocumentTests.cs # tests/Umbraco.Tests.Integration/ManagementApi/Policies/UpdateDocumentTests.cs # tests/Umbraco.Tests.Integration/ManagementApi/Preview/EndPreviewTests.cs # tests/Umbraco.Tests.Integration/ManagementApi/Preview/EnterPreviewTests.cs # tests/Umbraco.Tests.Integration/TestServerTest/UmbracoTestServerTestBase.cs * Updated test * Updates * Removed unnessecary test --------- Co-authored-by: Nhu Dinh <150406148+nhudinh0309@users.noreply.github.com> Co-authored-by: Zeegaan <skrivdetud@gmail.com> Co-authored-by: Nikolaj Geisle <70372949+Zeegaan@users.noreply.github.com>
2025-10-14 12:04:10 +02:00
await factory.DisposeAsync();
}
_factoryCache.Clear();
}
/// <summary>
/// Prepare a url before using <see cref="Client"/>.
/// This returns the url but also sets the HttpContext.request into to use this url.
/// </summary>
/// <returns>The string URL of the controller action.</returns>
protected string PrepareApiControllerUrl<T>(Expression<Func<T, object>> methodSelector)
where T : UmbracoApiController
{
var url = LinkGenerator.GetUmbracoApiService(methodSelector);
return PrepareUrl(url);
}
V14: Add authorization policies to Management API controllers - p2 (#15211) * Making ProblemDetails details more generic * Adding authorizer that can be replaces for external authz in handlers. Adding handler and requirement for UserBelongsToUserGroupInRequest policy * Adding method to get the GUID from claims * Adding service methods to check user group authz * Porting MustSatisfyRequirementAuthorizationHandler * Adding controllers authz * Fix return status code + produced response type * Moving to folder * Adding DenyLocalLogin policy scaffold * Implement a temp DenyLocalLoginHandler * Introducing a new Fobidden result * Fix comment * Introducing a helper class for authorizers * Changed nullability for GetCurrentUser * Changes from Attempt to Status + FIXME comments * Create a UserGroupAuthorizationStatus to be used in the future * Introduces a new authz status for checking media acess * Introducing a new permission service for media * Adding fixme * Adding more policy configurations * Adding Media policy requirement and handler * Adding media authorizer * Fix order of params * Adding duplicate code comment * Adding authz to media controllers * Migrating more logic from MediaPermissions.cs * Adding more MediaAuthorizationStatus-es * Handling of new authorization status * Fix comment * Adding NotFound case * Adding NewDenyLocalLoginIfConfigured policy && commenting [AllowAnonymous] where the policy is applied since it is already handled * Changed Forbid() to Forbidden() to get the correct status code * Remove policy that is applied on the base controller already * Implement and apply NewUmbracoFeatureEnabled policy * Renaming classes to add Permission in the name * Register permission services * Add FIXME * Introduce new IUserGroupPermissionService and refactor accordingly * Add single overload with default implementation * Adding user permission policy and related * Applying admin policy * Register all new policies * Better wording * Add default implementation for a single overload * Adding remarks to IContentPermissionService.cs * Supporting null as key in ContentPermissionService * Fix namespace * Reverting back to not supporting null as content key, but having dedicated implementation * Adding content authorizer with null values to represent root item * Removing null key support and adding dedicated implementation * Removing remarks * Adding content resource with null support * Removing null support * Adding requirement and status * Adding content authorizer + handlers * Applying policies to content controllers * Update comment * Handling of Authorization Statuses * More authz in controllers * Fix comments * New branch handler * Obsolete old implementation * Adding dedicated policies to root and bin * Adding a branch specific namespace * Bin specific requirement and namespace * Root specific requirement and namespace * Changing to new root policy * Refactoring * Save policies * Fix null check/reference * Add TODO comment * Create media root- and bin-specific policies, handlers, etc. * Apply correct policy in create and update media controllers * Apply root policy to move and sort controllers * Fix wording * Adding UserGroupAuthorizationStatusResult * Remove all AuthorizationStatusResult as we cannot get the specific AuthorizationStatus * Fixing Umbraco feature policy * Fix allow anonymous endpoints - the value returned from DenyLocalLoginHandler wasn't enough, we need to succeed DenyAnonymousAuthorizationRequirement as it is required for some of the endpoints that had the attribute * Apply DenyLocalLoginIfConfigured policy to corresponding re-implementation of PostSetInvitedUserPassword * Fix comment * Renaming performingUser to user and fixing comments * Rename helper method * Fix references * Re-add merge conflict deletion * Adding Backoffice requirement and relevant * Registering * Added a simple policy test * Fixed small test things and clean up * Temp solution * Added one more test and fix another static issue * Fix another merge conflict * Remove BackOfficePermissionRequirement and handler as they might not be necessary * Comment out again [AllowAnonymous] * Remove AuthorizationPolicies.BackOfficeAccessWithoutApproval policy as it might not be necessary * Fix temp implementation * Fix reference to correct handler * Apply authz policy to new publish/unpublish controllers * Fix comments * Removing duplicate ProducesResponseTypes * Added swagger documentation about the 401 and 403 * Added Resources to Media, User and UserGroup * Handle root, recycle bin and branch in the same handler * Handle both parent and target when moving * Check Ids for all sort requests * Xml docs * Clean up * Clean up * Fix build * Cleanup * Remove TODO * Added missing overload * Use yield * Adding some keys to check --------- Co-authored-by: Bjarke Berg <mail@bergmania.dk> Co-authored-by: Andreas Zerbst <andr317c@live.dk>
2023-12-11 08:25:29 +01:00
protected string GetManagementApiUrl<T>(Expression<Func<T, object>> methodSelector)
where T : ManagementApiControllerBase
{
MethodInfo? method = ExpressionHelper.GetMethodInfo(methodSelector);
IDictionary<string, object?> methodParams = ExpressionHelper.GetMethodParams(methodSelector) ?? new Dictionary<string, object?>();
// Remove the CancellationToken from the method params, this is automatically added by the framework
// So we do not want to add this to the query string
Auhorization: Cherrypicked integration tests from V15 (#20492) * V15 QA Added the authorization integration tests (#18419) * Added authorization integration tests * Removed unnecessary tests and update tests for preview controller * Updated to use the newest changes from v15/dev and added an override for the AuthenticateClientAsync to use the userGroupKey * Updated CompatibilitySuppressions to include changes from integration tests * Updated pipelines * Skips managementApi tests * Only run necessary tests * Added new schema per fixture to reduce test setup time * Fixed failing tests * Updated test setup * Updated test * Added suppression * Fixed failing tests * Updated addOnTeardown methods to protected * Added method for clearing the host * Added teardown * Updated model usage * Added a lot of cleanup for memory leak issues when running tests * Added CompatibilitySuppressions.xml * Updated tests * Cleaned up * Adjusted base classes * Updated pipeline * Updated CompatibilitySuppressions.xml * Updated test logging * Fixed reponse * Updated condition to skip tests * Updated tests, not done * Reworked test to expect correct responses with correct setup * Updated tests * More updates to tests * Updated tests * Cleaned up tests * Updated setup * Cleaned up tests to match setup * Cleaned up setup * Removed suppression * Fixed tests * Move order of checks * Fix naming * Formatting * Dispose of host * Keep track of if we're disposed * Compat suppression * Dont dispose * Fix failing tests * removed unused virtual * Updated CompatibilitySuppressions.xml --------- Co-authored-by: Andreas Zerbst <andr317c@live.dk> Co-authored-by: Zeegaan <skrivdetud@gmail.com> Co-authored-by: Nikolaj Geisle <70372949+Zeegaan@users.noreply.github.com> # Conflicts: # tests/Umbraco.Tests.Integration/CompatibilitySuppressions.xml # tests/Umbraco.Tests.Integration/ManagementApi/ManagementApiTest.cs # tests/Umbraco.Tests.Integration/ManagementApi/Policies/AllCultureControllerTests.cs # tests/Umbraco.Tests.Integration/ManagementApi/Policies/CreateDocumentTests.cs # tests/Umbraco.Tests.Integration/ManagementApi/Policies/UpdateDocumentTests.cs # tests/Umbraco.Tests.Integration/ManagementApi/Preview/EndPreviewTests.cs # tests/Umbraco.Tests.Integration/ManagementApi/Preview/EnterPreviewTests.cs # tests/Umbraco.Tests.Integration/TestServerTest/UmbracoTestServerTestBase.cs * Updated test * Updates * Removed unnessecary test --------- Co-authored-by: Nhu Dinh <150406148+nhudinh0309@users.noreply.github.com> Co-authored-by: Zeegaan <skrivdetud@gmail.com> Co-authored-by: Nikolaj Geisle <70372949+Zeegaan@users.noreply.github.com>
2025-10-14 12:04:10 +02:00
methodParams.Remove(methodParams.FirstOrDefault(x => x.Value is CancellationToken).Key);
methodParams["version"] = method?.GetCustomAttribute<MapToApiVersionAttribute>()?.Versions[0].MajorVersion.ToString();
return LinkGenerator.GetUmbracoControllerUrl(method.Name, ControllerExtensions.GetControllerName<T>(), null, methodParams);
V14: Add authorization policies to Management API controllers - p2 (#15211) * Making ProblemDetails details more generic * Adding authorizer that can be replaces for external authz in handlers. Adding handler and requirement for UserBelongsToUserGroupInRequest policy * Adding method to get the GUID from claims * Adding service methods to check user group authz * Porting MustSatisfyRequirementAuthorizationHandler * Adding controllers authz * Fix return status code + produced response type * Moving to folder * Adding DenyLocalLogin policy scaffold * Implement a temp DenyLocalLoginHandler * Introducing a new Fobidden result * Fix comment * Introducing a helper class for authorizers * Changed nullability for GetCurrentUser * Changes from Attempt to Status + FIXME comments * Create a UserGroupAuthorizationStatus to be used in the future * Introduces a new authz status for checking media acess * Introducing a new permission service for media * Adding fixme * Adding more policy configurations * Adding Media policy requirement and handler * Adding media authorizer * Fix order of params * Adding duplicate code comment * Adding authz to media controllers * Migrating more logic from MediaPermissions.cs * Adding more MediaAuthorizationStatus-es * Handling of new authorization status * Fix comment * Adding NotFound case * Adding NewDenyLocalLoginIfConfigured policy && commenting [AllowAnonymous] where the policy is applied since it is already handled * Changed Forbid() to Forbidden() to get the correct status code * Remove policy that is applied on the base controller already * Implement and apply NewUmbracoFeatureEnabled policy * Renaming classes to add Permission in the name * Register permission services * Add FIXME * Introduce new IUserGroupPermissionService and refactor accordingly * Add single overload with default implementation * Adding user permission policy and related * Applying admin policy * Register all new policies * Better wording * Add default implementation for a single overload * Adding remarks to IContentPermissionService.cs * Supporting null as key in ContentPermissionService * Fix namespace * Reverting back to not supporting null as content key, but having dedicated implementation * Adding content authorizer with null values to represent root item * Removing null key support and adding dedicated implementation * Removing remarks * Adding content resource with null support * Removing null support * Adding requirement and status * Adding content authorizer + handlers * Applying policies to content controllers * Update comment * Handling of Authorization Statuses * More authz in controllers * Fix comments * New branch handler * Obsolete old implementation * Adding dedicated policies to root and bin * Adding a branch specific namespace * Bin specific requirement and namespace * Root specific requirement and namespace * Changing to new root policy * Refactoring * Save policies * Fix null check/reference * Add TODO comment * Create media root- and bin-specific policies, handlers, etc. * Apply correct policy in create and update media controllers * Apply root policy to move and sort controllers * Fix wording * Adding UserGroupAuthorizationStatusResult * Remove all AuthorizationStatusResult as we cannot get the specific AuthorizationStatus * Fixing Umbraco feature policy * Fix allow anonymous endpoints - the value returned from DenyLocalLoginHandler wasn't enough, we need to succeed DenyAnonymousAuthorizationRequirement as it is required for some of the endpoints that had the attribute * Apply DenyLocalLoginIfConfigured policy to corresponding re-implementation of PostSetInvitedUserPassword * Fix comment * Renaming performingUser to user and fixing comments * Rename helper method * Fix references * Re-add merge conflict deletion * Adding Backoffice requirement and relevant * Registering * Added a simple policy test * Fixed small test things and clean up * Temp solution * Added one more test and fix another static issue * Fix another merge conflict * Remove BackOfficePermissionRequirement and handler as they might not be necessary * Comment out again [AllowAnonymous] * Remove AuthorizationPolicies.BackOfficeAccessWithoutApproval policy as it might not be necessary * Fix temp implementation * Fix reference to correct handler * Apply authz policy to new publish/unpublish controllers * Fix comments * Removing duplicate ProducesResponseTypes * Added swagger documentation about the 401 and 403 * Added Resources to Media, User and UserGroup * Handle root, recycle bin and branch in the same handler * Handle both parent and target when moving * Check Ids for all sort requests * Xml docs * Clean up * Clean up * Fix build * Cleanup * Remove TODO * Added missing overload * Use yield * Adding some keys to check --------- Co-authored-by: Bjarke Berg <mail@bergmania.dk> Co-authored-by: Andreas Zerbst <andr317c@live.dk>
2023-12-11 08:25:29 +01:00
}
/// <summary>
/// Prepare a url before using <see cref="Client"/>.
/// This returns the url but also sets the HttpContext.request into to use this url.
/// </summary>
/// <returns>The string URL of the controller action.</returns>
protected string PrepareSurfaceControllerUrl<T>(Expression<Func<T, object>> methodSelector)
where T : SurfaceController
{
var url = LinkGenerator.GetUmbracoSurfaceUrl(methodSelector);
return PrepareUrl(url);
}
/// <summary>
/// Prepare a url before using <see cref="Client"/>.
/// This returns the url but also sets the HttpContext.request into to use this url.
/// </summary>
/// <returns>The string URL of the controller action.</returns>
protected string PrepareUrl(string url)
{
IUmbracoContextFactory umbracoContextFactory = GetRequiredService<IUmbracoContextFactory>();
IHttpContextAccessor httpContextAccessor = GetRequiredService<IHttpContextAccessor>();
httpContextAccessor.HttpContext = new DefaultHttpContext
{
Request =
{
Scheme = "https",
Host = new HostString("localhost", 80),
Path = url,
QueryString = new QueryString(string.Empty)
}
};
umbracoContextFactory.EnsureUmbracoContext();
return url;
}
private IHostBuilder CreateHostBuilder()
{
IHostBuilder hostBuilder = Host.CreateDefaultBuilder()
.ConfigureUmbracoDefaults()
.ConfigureAppConfiguration((context, configBuilder) =>
{
context.HostingEnvironment = TestHelper.GetWebHostEnvironment();
configBuilder.Sources.Clear();
configBuilder.AddInMemoryCollection(InMemoryConfiguration);
configBuilder.AddConfiguration(GlobalSetupTeardown.TestConfiguration);
Configuration = configBuilder.Build();
})
.ConfigureWebHost(builder =>
{
builder.ConfigureServices((context, services) =>
2022-02-12 11:40:39 +00:00
{
context.HostingEnvironment = TestHelper.GetWebHostEnvironment();
ConfigureServices(services);
ConfigureTestServices(services);
services.AddUnique(CreateLoggerFactory());
if (!TestOptions.Boot)
{
// If boot is false, we don't want the CoreRuntime hosted service to start
// So we replace it with a Mock
services.AddUnique(Mock.Of<IRuntime>());
}
});
// call startup
builder.Configure(Configure);
})
.UseDefaultServiceProvider(cfg =>
{
// These default to true *if* WebHostEnvironment.EnvironmentName == Development
// When running tests, EnvironmentName used to be null on the mock that we register into services.
// Enable opt in for tests so that validation occurs regardless of environment name.
// Would be nice to have this on for UmbracoIntegrationTest also but requires a lot more effort to resolve issues.
cfg.ValidateOnBuild = true;
cfg.ValidateScopes = true;
});
return hostBuilder;
}
protected virtual T GetRequiredService<T>() => Factory.Services.GetRequiredService<T>();
protected void ConfigureServices(IServiceCollection services)
{
services.AddTransient<TestUmbracoDatabaseFactoryProvider>();
TypeLoader typeLoader = services.AddTypeLoader(
GetType().Assembly,
TestHelper.ConsoleLoggerFactory,
Auhorization: Cherrypicked integration tests from V15 (#20492) * V15 QA Added the authorization integration tests (#18419) * Added authorization integration tests * Removed unnecessary tests and update tests for preview controller * Updated to use the newest changes from v15/dev and added an override for the AuthenticateClientAsync to use the userGroupKey * Updated CompatibilitySuppressions to include changes from integration tests * Updated pipelines * Skips managementApi tests * Only run necessary tests * Added new schema per fixture to reduce test setup time * Fixed failing tests * Updated test setup * Updated test * Added suppression * Fixed failing tests * Updated addOnTeardown methods to protected * Added method for clearing the host * Added teardown * Updated model usage * Added a lot of cleanup for memory leak issues when running tests * Added CompatibilitySuppressions.xml * Updated tests * Cleaned up * Adjusted base classes * Updated pipeline * Updated CompatibilitySuppressions.xml * Updated test logging * Fixed reponse * Updated condition to skip tests * Updated tests, not done * Reworked test to expect correct responses with correct setup * Updated tests * More updates to tests * Updated tests * Cleaned up tests * Updated setup * Cleaned up tests to match setup * Cleaned up setup * Removed suppression * Fixed tests * Move order of checks * Fix naming * Formatting * Dispose of host * Keep track of if we're disposed * Compat suppression * Dont dispose * Fix failing tests * removed unused virtual * Updated CompatibilitySuppressions.xml --------- Co-authored-by: Andreas Zerbst <andr317c@live.dk> Co-authored-by: Zeegaan <skrivdetud@gmail.com> Co-authored-by: Nikolaj Geisle <70372949+Zeegaan@users.noreply.github.com> # Conflicts: # tests/Umbraco.Tests.Integration/CompatibilitySuppressions.xml # tests/Umbraco.Tests.Integration/ManagementApi/ManagementApiTest.cs # tests/Umbraco.Tests.Integration/ManagementApi/Policies/AllCultureControllerTests.cs # tests/Umbraco.Tests.Integration/ManagementApi/Policies/CreateDocumentTests.cs # tests/Umbraco.Tests.Integration/ManagementApi/Policies/UpdateDocumentTests.cs # tests/Umbraco.Tests.Integration/ManagementApi/Preview/EndPreviewTests.cs # tests/Umbraco.Tests.Integration/ManagementApi/Preview/EnterPreviewTests.cs # tests/Umbraco.Tests.Integration/TestServerTest/UmbracoTestServerTestBase.cs * Updated test * Updates * Removed unnessecary test --------- Co-authored-by: Nhu Dinh <150406148+nhudinh0309@users.noreply.github.com> Co-authored-by: Zeegaan <skrivdetud@gmail.com> Co-authored-by: Nikolaj Geisle <70372949+Zeegaan@users.noreply.github.com>
2025-10-14 12:04:10 +02:00
Configuration);
services.AddLogger(TestHelper.GetWebHostEnvironment(), Configuration);
Remove the non-controversial, straightforward obsoleted constructs for Umbraco 16 (#18661) * Removed obsoletes from IConfigManipulator. * Removed obsolete models builder extensions. * Removed the obsolete ContentDashboardSettings. * Removed the obsolete InstallMissingDatabase setting on GlobalSettings. * Removed obsolete NuCache settings. * Removed obsolete RuntimeMinificationSettings. * Removed obsolete health check constant. * Removed obsolete icon constant. * Removed obsolete telemetry constant. * Removed obsolete property and constructor on UmbracoBuilder. * Removed obsolete constructor on AuditNotificationsHandler. * Removed obsolete constructor on HTTP header health checks. * Removed obsolete constructor on MediaFileManager. * Removed obsolete GetDefaultFileContent on ViewHelper. * Remove obsoleted methods on embed providers. * Fix tests. * Removed obsolete constructors on BlockEditorDataConverter. * Removed obsolete SeedCacheDuration property on CacheSettings. * Removed obsolete PublishCulture on ContentRepositoryExtensions. * Removed obsolete MonitorLock. * Removed obsolete synchronous HasSavedValues from IDataTypeUsageService and IDataTypeUsageRepository. * Removed obsolete HasSavedPropertyValues from IPropertyTypeUsageService and IPropertyTypeUsageRepository. * Removed obsolete methods in ITrackedReferencesService and ITrackedReferencesRepository. * Removed obsolete DateValueEditor constructors. * Removed obsolete GetAutomaticRelationTypesAliases. * Removed obsolete constructor on TextOnlyValueEditor. * Removed obsolete constructors on RegexValidator and RequiredValidator. * Removed obsolete constructs on SliderValueConverter and TagsValueConverter. * Removed obsolete GetContentType methods from IPublishedCache. * Removed ContentFinderByIdPath. * Removed obsolete constructor on DefaultMediaUrlProvider. * Removed obsolete constructor on Domain. * Removed obsolete constructor on PublishedRequest. * Removed obsolete methods on CheckPermissions. * Removed obsolete GetUserId from IBackOfficeSecurity. * Removed obsolete methods on LegacyPasswordSecurity. * Removed obsolete constructors on AuditService. * Removed obsolete methods on IContentEditingService. * Remove obsolete constructors and methods on ContentService/IContentService. * Removed obsolete constructor in ContentTypeEditingService. * Removed obsolete constructor in MediaTypeEditingService. * Removed obsolete constructor in MemberTypeEditingService. * Removed obsolete constructor in ContentTypeService. * Removed obsolete constructors in ContentTypeServiceBase. * Removed obsolete constructors and methods in ContentVersionService. * Removed obsolete constructor in DataTypeUsageService. * Removed obsolete constructor in DomainService. * Removed obsolete constructor in FileService. * Removes obsolete AttemptMove from IContentService. * Removes obsolete SetPreventCleanup from IContentVersionService. * Removes obsolete GetReferences from IDataTypeService. * Removed obsolete SetConsentLevel from IMetricsConsentService. * Removed obsolete methods from IPackageDataInstallation. * Removed obsolete methods from IPackagingService. * Removed obsolete methods on ITwoFactorLoginService. Removed obsolete ITemporaryMediaService. * Removed obsolete constructor from MediaService, MemberTypeService and MediaTypeService. * More obsolete constructors. * Removed obsoleted overloads on IPropertyValidationService. * Fixed build for tests. * Removed obsolete constructor for PublicAccessService, UserService and RelationService. * Removed GetDefaultMemberType. * Removed obsolete user group functionality from IUserService. * Removed obsolete extension methods on IUserService. * Removed obsolete method from ITelemetryService. * Removed obsolete UdiParserServiceConnectors. * Removed obsolete method on ICookieManager. * Removed obsolete DynamicContext. * Removed obsolete XmlHelper. * Fixed failing integration tests. * Removed obsoletes in Umbraco.Cms.Api.Common * Removed obsoletes in Umbraco.Cms.Api.Delivery * Removed obsoletes in Umbraco.Cms.Api.Management * Removed obsoletes in Umbraco.Examine.Lucene * Removed obsoletes in Umbraco.Infrastructure * Fix failing delivery API contract integration test. * Made integration tests internal. * Removed obsoletes from web projects. * Fix build. * Removed Twitter OEmbed provider * Removed obsolete constructor on PublishedDataType. * Removed obsolete constructors on PublishedCacheBase. * Removed the obsolete PropertyEditorTagsExtensions. * Removed obsoletion properties on configuration response models (#18697) * Removed obsolete methods from server-side models. * Update client-side types and sdk. * Update client-side files. * Removed obsoletion of Utf8ToAsciiConverter.ToAsciiString overload. (#18694) * Removed obsolete method in UserService. (#18710) * Removed obsoleted group alias keys from being publicly available. (#18682) * Removed unneceessary ApiVersion attribute. * Clean-up obsoletions on MemberService (#18703) * Removed obsoleted method on MemberService, added future obsoletion to interface and updated all callers. * Removed obsoletion on member service method that's not obsolete on the interface.
2025-03-21 18:02:31 +01:00
var builder = new UmbracoBuilder(services, Configuration, typeLoader, TestHelper.ConsoleLoggerFactory, TestHelper.Profiler, AppCaches.NoCache);
Auhorization: Cherrypicked integration tests from V15 (#20492) * V15 QA Added the authorization integration tests (#18419) * Added authorization integration tests * Removed unnecessary tests and update tests for preview controller * Updated to use the newest changes from v15/dev and added an override for the AuthenticateClientAsync to use the userGroupKey * Updated CompatibilitySuppressions to include changes from integration tests * Updated pipelines * Skips managementApi tests * Only run necessary tests * Added new schema per fixture to reduce test setup time * Fixed failing tests * Updated test setup * Updated test * Added suppression * Fixed failing tests * Updated addOnTeardown methods to protected * Added method for clearing the host * Added teardown * Updated model usage * Added a lot of cleanup for memory leak issues when running tests * Added CompatibilitySuppressions.xml * Updated tests * Cleaned up * Adjusted base classes * Updated pipeline * Updated CompatibilitySuppressions.xml * Updated test logging * Fixed reponse * Updated condition to skip tests * Updated tests, not done * Reworked test to expect correct responses with correct setup * Updated tests * More updates to tests * Updated tests * Cleaned up tests * Updated setup * Cleaned up tests to match setup * Cleaned up setup * Removed suppression * Fixed tests * Move order of checks * Fix naming * Formatting * Dispose of host * Keep track of if we're disposed * Compat suppression * Dont dispose * Fix failing tests * removed unused virtual * Updated CompatibilitySuppressions.xml --------- Co-authored-by: Andreas Zerbst <andr317c@live.dk> Co-authored-by: Zeegaan <skrivdetud@gmail.com> Co-authored-by: Nikolaj Geisle <70372949+Zeegaan@users.noreply.github.com> # Conflicts: # tests/Umbraco.Tests.Integration/CompatibilitySuppressions.xml # tests/Umbraco.Tests.Integration/ManagementApi/ManagementApiTest.cs # tests/Umbraco.Tests.Integration/ManagementApi/Policies/AllCultureControllerTests.cs # tests/Umbraco.Tests.Integration/ManagementApi/Policies/CreateDocumentTests.cs # tests/Umbraco.Tests.Integration/ManagementApi/Policies/UpdateDocumentTests.cs # tests/Umbraco.Tests.Integration/ManagementApi/Preview/EndPreviewTests.cs # tests/Umbraco.Tests.Integration/ManagementApi/Preview/EnterPreviewTests.cs # tests/Umbraco.Tests.Integration/TestServerTest/UmbracoTestServerTestBase.cs * Updated test * Updates * Removed unnessecary test --------- Co-authored-by: Nhu Dinh <150406148+nhudinh0309@users.noreply.github.com> Co-authored-by: Zeegaan <skrivdetud@gmail.com> Co-authored-by: Nikolaj Geisle <70372949+Zeegaan@users.noreply.github.com>
2025-10-14 12:04:10 +02:00
builder.Services.AddTransient<IHostedService>(sp =>
new TestDatabaseHostedLifecycleService(() => UseTestDatabase(sp)));
builder
.AddConfiguration()
.AddUmbracoCore()
.AddWebComponents()
V15: Hybrid Caching (#16938) * Update to dotnet 9 and update nuget packages * Update umbraco code version * Update Directory.Build.props Co-authored-by: Elitsa Marinovska <21998037+elit0451@users.noreply.github.com> * Include preview version in pipeline * update template projects * update global json with specific version * Update version.json to v15 * Rename TrimStart and TrimEnd to string specific * Rename to Exact * Update global.json Co-authored-by: Ronald Barendse <ronald@barend.se> * Remove includePreviewVersion * Rename to trim exact * Add new Hybridcache project * Add tests * Start implementing PublishedContent.cs * Implement repository for content * Refactor to use async everywhere * Add cache refresher * make public as needed for serialization * Use content type cache to get content type out * Refactor to use ContentCacheNode model, that goes in the memory cache * Remove content node kit as its not needed * Implement tests for ensuring caching * Implement better asserts * Implement published property * Refactor to use mapping * Rename to document tests * Update to test properties * Create more tests * Refactor mock tests into own file * Update property test * Fix published version of content * Change default cache level to elements * Refactor to always have draft * Refactor to not use PublishedModelFactory * Added tests * Added and updated tests * Fixed tests * Don't return empty object with id * More tests * Added key * Another key * Refactor CacheService to be responsible for using the hybrid cache * Use notification handler to remove deleted content from cache * Add more tests for missing functions * Implement missing methods * Remove HasContent as it pertains to routing * Fik up test * formatting * refactor variable names * Implement variant tests * Map all the published content properties * Get item out of cache first, to assert updated * Implement member cache * Add member test * Implement media cache * Implement property tests for media tests * Refactor tests to use extension method * Add more media tests * Refactor properties to no longer have element caching * Don't use property cache level * Start implementing seeding * Only seed when main * Add Immutable for performance * Implement permanent seeding of content * Implement cache settings * Implement tests for seeding * Update package version * start refactoring nurepo * Refactor so draft & published nodes are cached individually * Refactor RefreshContent to take node instead of IContent * Refactor media to also use cache nodes * Remove member from repo as it isn't cached * Refactor media to not include preview, as media has no draft * create new benchmark project * POC Integration benchmarks with custom api controllers * Start implementing content picker tests * Implement domain cache * Rework content cache to implement interface * Start implementing elements cache * Implement published snapshot service * Publish snapshot tests * Use snapshot for elements cache * Create test proving we don't clear cache when updating content picker * Clear entire elements cache * Remove properties from element cache, when content gets updated. * Rename methods to async * Refactor to use old cache interfaces instead of new ones * Remove snapshot, as it is no longer needed * Fix tests building * Refactor domaincache to not have snapshots * Delete benchmarks * Delete benchmarks * Add HybridCacheProject to Umbraco * Add comment to route value transformer * Implement is draft * remove snapshot from property * V15 updated the hybrid caching integration tests to use ContentEditingService (#16947) * Added builder extension withParentKey * Created builder with ContentEditingService * Added usage of the ContentEditingService to SETUP * Started using ContentEditingService builder in tests * Updated builder extensions * Fixed builder * Clean up * Clean up, not done * Added Ids * Remove entries from cache on delete * Fix up seeding logic * Don't register hybrid cache twice * Change seeded entry options * Update hybrid cache package * Fix up published property to work with delivery api again * Fix dependency injection to work with tests * Fix naming * Dont make caches nullable * Make content node sealed * Remove path and other unused from content node * Remove hacky 2 phase ctor * Refactor to actually set content templates * Remove umbraco context * Remove "HasBy" methods * rename property data * Delete obsolete legacy stuff * Add todo for making expiration configurable * Add todo in UmbracoContext * Add clarifying comment in content factory * Remove xml stuff from published property * Fix according to review * Make content type cache injectible * Make content type cache injectible * Rename to database cache repository * Rename to document cache * Add TODO * Refactor to async * Rename to async * Make everything async * Remove duplicate line from json schema * Move Hybrid cache project * Remove leftover file * Refactor to use keys * Refactor published content to no longer have content data, as it is on the node itself * Refactor to member to use proper content node ctor * Move tests to own folder * Add immutable objects to property and content data for performance * Make property data public * Fix member caching to be singleton * Obsolete GetContentType * Remove todo * Fix naming * Fix lots of exposed errors due to scope test * Add final scope tests * Rename to document cache service * Rename test files * Create new doc type tests * Add ignore to tests * Start implementing refresh for content type save * Clear contenttype cache when contenttype is updated * Fix test Teh contenttype is not upated unless the property is dirty * Use init for ContentSourceDto * Fix get by key in PublishedContentTypeCache * Remove ContentType from PublishedContentTypeCache when contenttype is deleted * Update to preview 7 * Fix versions * Increase timeout for sqlite integration tests * Undo timeout increase * Try and undo init change to ContentSourceDto * That wasn't it chief * Try and make DomainAndUrlsTests non NonParallelizable * Update versions * Only run cache tests on linux for now --------- Co-authored-by: Elitsa Marinovska <21998037+elit0451@users.noreply.github.com> Co-authored-by: Ronald Barendse <ronald@barend.se> Co-authored-by: Andreas Zerbst <andr317c@live.dk> Co-authored-by: Sven Geusens <sge@umbraco.dk> Co-authored-by: Andreas Zerbst <73799582+andr317c@users.noreply.github.com> Co-authored-by: nikolajlauridsen <nikolajlauridsen@protonmail.ch>
2024-09-10 00:49:18 +09:00
.AddUmbracoHybridCache()
.AddBackOfficeCore()
.AddBackOfficeAuthentication()
.AddBackOfficeIdentity()
.AddMembersIdentity()
// .AddBackOfficeAuthorizationPolicies(TestAuthHandler.TestAuthenticationScheme)
.AddMvcAndRazor(mvcBuilding: mvcBuilder =>
{
// Adds Umbraco.Web.Common
mvcBuilder.AddApplicationPart(typeof(RenderController).Assembly);
// Adds Umbraco.Web.Website
mvcBuilder.AddApplicationPart(typeof(SurfaceController).Assembly);
V14: Add authorization policies to Management API controllers - p2 (#15211) * Making ProblemDetails details more generic * Adding authorizer that can be replaces for external authz in handlers. Adding handler and requirement for UserBelongsToUserGroupInRequest policy * Adding method to get the GUID from claims * Adding service methods to check user group authz * Porting MustSatisfyRequirementAuthorizationHandler * Adding controllers authz * Fix return status code + produced response type * Moving to folder * Adding DenyLocalLogin policy scaffold * Implement a temp DenyLocalLoginHandler * Introducing a new Fobidden result * Fix comment * Introducing a helper class for authorizers * Changed nullability for GetCurrentUser * Changes from Attempt to Status + FIXME comments * Create a UserGroupAuthorizationStatus to be used in the future * Introduces a new authz status for checking media acess * Introducing a new permission service for media * Adding fixme * Adding more policy configurations * Adding Media policy requirement and handler * Adding media authorizer * Fix order of params * Adding duplicate code comment * Adding authz to media controllers * Migrating more logic from MediaPermissions.cs * Adding more MediaAuthorizationStatus-es * Handling of new authorization status * Fix comment * Adding NotFound case * Adding NewDenyLocalLoginIfConfigured policy && commenting [AllowAnonymous] where the policy is applied since it is already handled * Changed Forbid() to Forbidden() to get the correct status code * Remove policy that is applied on the base controller already * Implement and apply NewUmbracoFeatureEnabled policy * Renaming classes to add Permission in the name * Register permission services * Add FIXME * Introduce new IUserGroupPermissionService and refactor accordingly * Add single overload with default implementation * Adding user permission policy and related * Applying admin policy * Register all new policies * Better wording * Add default implementation for a single overload * Adding remarks to IContentPermissionService.cs * Supporting null as key in ContentPermissionService * Fix namespace * Reverting back to not supporting null as content key, but having dedicated implementation * Adding content authorizer with null values to represent root item * Removing null key support and adding dedicated implementation * Removing remarks * Adding content resource with null support * Removing null support * Adding requirement and status * Adding content authorizer + handlers * Applying policies to content controllers * Update comment * Handling of Authorization Statuses * More authz in controllers * Fix comments * New branch handler * Obsolete old implementation * Adding dedicated policies to root and bin * Adding a branch specific namespace * Bin specific requirement and namespace * Root specific requirement and namespace * Changing to new root policy * Refactoring * Save policies * Fix null check/reference * Add TODO comment * Create media root- and bin-specific policies, handlers, etc. * Apply correct policy in create and update media controllers * Apply root policy to move and sort controllers * Fix wording * Adding UserGroupAuthorizationStatusResult * Remove all AuthorizationStatusResult as we cannot get the specific AuthorizationStatus * Fixing Umbraco feature policy * Fix allow anonymous endpoints - the value returned from DenyLocalLoginHandler wasn't enough, we need to succeed DenyAnonymousAuthorizationRequirement as it is required for some of the endpoints that had the attribute * Apply DenyLocalLoginIfConfigured policy to corresponding re-implementation of PostSetInvitedUserPassword * Fix comment * Renaming performingUser to user and fixing comments * Rename helper method * Fix references * Re-add merge conflict deletion * Adding Backoffice requirement and relevant * Registering * Added a simple policy test * Fixed small test things and clean up * Temp solution * Added one more test and fix another static issue * Fix another merge conflict * Remove BackOfficePermissionRequirement and handler as they might not be necessary * Comment out again [AllowAnonymous] * Remove AuthorizationPolicies.BackOfficeAccessWithoutApproval policy as it might not be necessary * Fix temp implementation * Fix reference to correct handler * Apply authz policy to new publish/unpublish controllers * Fix comments * Removing duplicate ProducesResponseTypes * Added swagger documentation about the 401 and 403 * Added Resources to Media, User and UserGroup * Handle root, recycle bin and branch in the same handler * Handle both parent and target when moving * Check Ids for all sort requests * Xml docs * Clean up * Clean up * Fix build * Cleanup * Remove TODO * Added missing overload * Use yield * Adding some keys to check --------- Co-authored-by: Bjarke Berg <mail@bergmania.dk> Co-authored-by: Andreas Zerbst <andr317c@live.dk>
2023-12-11 08:25:29 +01:00
// Adds Umbraco.Cms.Api.ManagementApi
mvcBuilder.AddApplicationPart(typeof(ModelsBuilderControllerBase).Assembly);
// Adds Umbraco.Cms.Api.DeliveryApi
mvcBuilder.AddApplicationPart(typeof(ContentApiItemControllerBase).Assembly);
// Adds Umbraco.Tests.Integration
mvcBuilder.AddApplicationPart(typeof(UmbracoTestServerTestBase).Assembly);
CustomMvcSetup(mvcBuilder);
})
.AddWebsite()
.AddUmbracoSqlServerSupport()
.AddUmbracoSqliteSupport()
.AddDeliveryApi()
V14: Add authorization policies to Management API controllers - p2 (#15211) * Making ProblemDetails details more generic * Adding authorizer that can be replaces for external authz in handlers. Adding handler and requirement for UserBelongsToUserGroupInRequest policy * Adding method to get the GUID from claims * Adding service methods to check user group authz * Porting MustSatisfyRequirementAuthorizationHandler * Adding controllers authz * Fix return status code + produced response type * Moving to folder * Adding DenyLocalLogin policy scaffold * Implement a temp DenyLocalLoginHandler * Introducing a new Fobidden result * Fix comment * Introducing a helper class for authorizers * Changed nullability for GetCurrentUser * Changes from Attempt to Status + FIXME comments * Create a UserGroupAuthorizationStatus to be used in the future * Introduces a new authz status for checking media acess * Introducing a new permission service for media * Adding fixme * Adding more policy configurations * Adding Media policy requirement and handler * Adding media authorizer * Fix order of params * Adding duplicate code comment * Adding authz to media controllers * Migrating more logic from MediaPermissions.cs * Adding more MediaAuthorizationStatus-es * Handling of new authorization status * Fix comment * Adding NotFound case * Adding NewDenyLocalLoginIfConfigured policy && commenting [AllowAnonymous] where the policy is applied since it is already handled * Changed Forbid() to Forbidden() to get the correct status code * Remove policy that is applied on the base controller already * Implement and apply NewUmbracoFeatureEnabled policy * Renaming classes to add Permission in the name * Register permission services * Add FIXME * Introduce new IUserGroupPermissionService and refactor accordingly * Add single overload with default implementation * Adding user permission policy and related * Applying admin policy * Register all new policies * Better wording * Add default implementation for a single overload * Adding remarks to IContentPermissionService.cs * Supporting null as key in ContentPermissionService * Fix namespace * Reverting back to not supporting null as content key, but having dedicated implementation * Adding content authorizer with null values to represent root item * Removing null key support and adding dedicated implementation * Removing remarks * Adding content resource with null support * Removing null support * Adding requirement and status * Adding content authorizer + handlers * Applying policies to content controllers * Update comment * Handling of Authorization Statuses * More authz in controllers * Fix comments * New branch handler * Obsolete old implementation * Adding dedicated policies to root and bin * Adding a branch specific namespace * Bin specific requirement and namespace * Root specific requirement and namespace * Changing to new root policy * Refactoring * Save policies * Fix null check/reference * Add TODO comment * Create media root- and bin-specific policies, handlers, etc. * Apply correct policy in create and update media controllers * Apply root policy to move and sort controllers * Fix wording * Adding UserGroupAuthorizationStatusResult * Remove all AuthorizationStatusResult as we cannot get the specific AuthorizationStatus * Fixing Umbraco feature policy * Fix allow anonymous endpoints - the value returned from DenyLocalLoginHandler wasn't enough, we need to succeed DenyAnonymousAuthorizationRequirement as it is required for some of the endpoints that had the attribute * Apply DenyLocalLoginIfConfigured policy to corresponding re-implementation of PostSetInvitedUserPassword * Fix comment * Renaming performingUser to user and fixing comments * Rename helper method * Fix references * Re-add merge conflict deletion * Adding Backoffice requirement and relevant * Registering * Added a simple policy test * Fixed small test things and clean up * Temp solution * Added one more test and fix another static issue * Fix another merge conflict * Remove BackOfficePermissionRequirement and handler as they might not be necessary * Comment out again [AllowAnonymous] * Remove AuthorizationPolicies.BackOfficeAccessWithoutApproval policy as it might not be necessary * Fix temp implementation * Fix reference to correct handler * Apply authz policy to new publish/unpublish controllers * Fix comments * Removing duplicate ProducesResponseTypes * Added swagger documentation about the 401 and 403 * Added Resources to Media, User and UserGroup * Handle root, recycle bin and branch in the same handler * Handle both parent and target when moving * Check Ids for all sort requests * Xml docs * Clean up * Clean up * Fix build * Cleanup * Remove TODO * Added missing overload * Use yield * Adding some keys to check --------- Co-authored-by: Bjarke Berg <mail@bergmania.dk> Co-authored-by: Andreas Zerbst <andr317c@live.dk>
2023-12-11 08:25:29 +01:00
.AddUmbracoManagementApi()
Add member auth to the Delivery API (#14730) * Refactor OpenIddict for shared usage between APIs + implement member authentication and handling within the Delivery API * Make SwaggerRouteTemplatePipelineFilter UI config overridable * Enable token revocation + rename logout endpoint to signout * Add default implementation of SwaggerGenOptions configuration for enabling Delivery API member auth in Swagger * Correct notification handling when (un)protecting content * Fixing integration test framework * Cleanup test to not execute some composers twice * Update paths to match docs * Return Forbidden when a member is authorized but not allowed to access the requested resource * Cleanup * Rename RequestMemberService to RequestMemberAccessService * Rename badly named variable * Review comments * Hide the auth controller from Swagger * Remove semaphore * Add security requirements for content API operations in Swagger * Hide the back-office auth endpoints from Swagger * Fix merge * Update back-office API auth endpoint paths + add revoke and sign-out endpoints (as of now they do not exist, a separate task will fix that) * Swap endpoint order to maintain backwards compat with the current login screen for new back-office (will be swapped back again to ensure correct .well-known endpoints, see FIXME comment) * Make "items by IDs" endpoint support member auth * Add 401 and 403 to "items by IDs" endpoint responses --------- Co-authored-by: Bjarke Berg <mail@bergmania.dk> Co-authored-by: Elitsa <elm@umbraco.dk>
2023-09-26 09:22:45 +02:00
.AddComposers()
.AddTestServices(TestHelper); // This is the important one!
CustomTestSetup(builder);
Add member auth to the Delivery API (#14730) * Refactor OpenIddict for shared usage between APIs + implement member authentication and handling within the Delivery API * Make SwaggerRouteTemplatePipelineFilter UI config overridable * Enable token revocation + rename logout endpoint to signout * Add default implementation of SwaggerGenOptions configuration for enabling Delivery API member auth in Swagger * Correct notification handling when (un)protecting content * Fixing integration test framework * Cleanup test to not execute some composers twice * Update paths to match docs * Return Forbidden when a member is authorized but not allowed to access the requested resource * Cleanup * Rename RequestMemberService to RequestMemberAccessService * Rename badly named variable * Review comments * Hide the auth controller from Swagger * Remove semaphore * Add security requirements for content API operations in Swagger * Hide the back-office auth endpoints from Swagger * Fix merge * Update back-office API auth endpoint paths + add revoke and sign-out endpoints (as of now they do not exist, a separate task will fix that) * Swap endpoint order to maintain backwards compat with the current login screen for new back-office (will be swapped back again to ensure correct .well-known endpoints, see FIXME comment) * Make "items by IDs" endpoint support member auth * Add 401 and 403 to "items by IDs" endpoint responses --------- Co-authored-by: Bjarke Berg <mail@bergmania.dk> Co-authored-by: Elitsa <elm@umbraco.dk>
2023-09-26 09:22:45 +02:00
builder.Build();
}
protected void Configure(IApplicationBuilder app)
{
app.UseUmbraco()
.WithMiddleware(u =>
{
u.UseBackOffice();
u.UseWebsite();
})
.WithEndpoints(u =>
{
u.UseBackOfficeEndpoints();
u.UseWebsiteEndpoints();
});
}
}
}
V14: Add authorization policies to Management API controllers - p2 (#15211) * Making ProblemDetails details more generic * Adding authorizer that can be replaces for external authz in handlers. Adding handler and requirement for UserBelongsToUserGroupInRequest policy * Adding method to get the GUID from claims * Adding service methods to check user group authz * Porting MustSatisfyRequirementAuthorizationHandler * Adding controllers authz * Fix return status code + produced response type * Moving to folder * Adding DenyLocalLogin policy scaffold * Implement a temp DenyLocalLoginHandler * Introducing a new Fobidden result * Fix comment * Introducing a helper class for authorizers * Changed nullability for GetCurrentUser * Changes from Attempt to Status + FIXME comments * Create a UserGroupAuthorizationStatus to be used in the future * Introduces a new authz status for checking media acess * Introducing a new permission service for media * Adding fixme * Adding more policy configurations * Adding Media policy requirement and handler * Adding media authorizer * Fix order of params * Adding duplicate code comment * Adding authz to media controllers * Migrating more logic from MediaPermissions.cs * Adding more MediaAuthorizationStatus-es * Handling of new authorization status * Fix comment * Adding NotFound case * Adding NewDenyLocalLoginIfConfigured policy && commenting [AllowAnonymous] where the policy is applied since it is already handled * Changed Forbid() to Forbidden() to get the correct status code * Remove policy that is applied on the base controller already * Implement and apply NewUmbracoFeatureEnabled policy * Renaming classes to add Permission in the name * Register permission services * Add FIXME * Introduce new IUserGroupPermissionService and refactor accordingly * Add single overload with default implementation * Adding user permission policy and related * Applying admin policy * Register all new policies * Better wording * Add default implementation for a single overload * Adding remarks to IContentPermissionService.cs * Supporting null as key in ContentPermissionService * Fix namespace * Reverting back to not supporting null as content key, but having dedicated implementation * Adding content authorizer with null values to represent root item * Removing null key support and adding dedicated implementation * Removing remarks * Adding content resource with null support * Removing null support * Adding requirement and status * Adding content authorizer + handlers * Applying policies to content controllers * Update comment * Handling of Authorization Statuses * More authz in controllers * Fix comments * New branch handler * Obsolete old implementation * Adding dedicated policies to root and bin * Adding a branch specific namespace * Bin specific requirement and namespace * Root specific requirement and namespace * Changing to new root policy * Refactoring * Save policies * Fix null check/reference * Add TODO comment * Create media root- and bin-specific policies, handlers, etc. * Apply correct policy in create and update media controllers * Apply root policy to move and sort controllers * Fix wording * Adding UserGroupAuthorizationStatusResult * Remove all AuthorizationStatusResult as we cannot get the specific AuthorizationStatus * Fixing Umbraco feature policy * Fix allow anonymous endpoints - the value returned from DenyLocalLoginHandler wasn't enough, we need to succeed DenyAnonymousAuthorizationRequirement as it is required for some of the endpoints that had the attribute * Apply DenyLocalLoginIfConfigured policy to corresponding re-implementation of PostSetInvitedUserPassword * Fix comment * Renaming performingUser to user and fixing comments * Rename helper method * Fix references * Re-add merge conflict deletion * Adding Backoffice requirement and relevant * Registering * Added a simple policy test * Fixed small test things and clean up * Temp solution * Added one more test and fix another static issue * Fix another merge conflict * Remove BackOfficePermissionRequirement and handler as they might not be necessary * Comment out again [AllowAnonymous] * Remove AuthorizationPolicies.BackOfficeAccessWithoutApproval policy as it might not be necessary * Fix temp implementation * Fix reference to correct handler * Apply authz policy to new publish/unpublish controllers * Fix comments * Removing duplicate ProducesResponseTypes * Added swagger documentation about the 401 and 403 * Added Resources to Media, User and UserGroup * Handle root, recycle bin and branch in the same handler * Handle both parent and target when moving * Check Ids for all sort requests * Xml docs * Clean up * Clean up * Fix build * Cleanup * Remove TODO * Added missing overload * Use yield * Adding some keys to check --------- Co-authored-by: Bjarke Berg <mail@bergmania.dk> Co-authored-by: Andreas Zerbst <andr317c@live.dk>
2023-12-11 08:25:29 +01:00
public class TestDatabaseHostedLifecycleService : IHostedLifecycleService
{
private readonly Action _action;
public TestDatabaseHostedLifecycleService(Action action)
{
_action = action;
}
Auhorization: Cherrypicked integration tests from V15 (#20492) * V15 QA Added the authorization integration tests (#18419) * Added authorization integration tests * Removed unnecessary tests and update tests for preview controller * Updated to use the newest changes from v15/dev and added an override for the AuthenticateClientAsync to use the userGroupKey * Updated CompatibilitySuppressions to include changes from integration tests * Updated pipelines * Skips managementApi tests * Only run necessary tests * Added new schema per fixture to reduce test setup time * Fixed failing tests * Updated test setup * Updated test * Added suppression * Fixed failing tests * Updated addOnTeardown methods to protected * Added method for clearing the host * Added teardown * Updated model usage * Added a lot of cleanup for memory leak issues when running tests * Added CompatibilitySuppressions.xml * Updated tests * Cleaned up * Adjusted base classes * Updated pipeline * Updated CompatibilitySuppressions.xml * Updated test logging * Fixed reponse * Updated condition to skip tests * Updated tests, not done * Reworked test to expect correct responses with correct setup * Updated tests * More updates to tests * Updated tests * Cleaned up tests * Updated setup * Cleaned up tests to match setup * Cleaned up setup * Removed suppression * Fixed tests * Move order of checks * Fix naming * Formatting * Dispose of host * Keep track of if we're disposed * Compat suppression * Dont dispose * Fix failing tests * removed unused virtual * Updated CompatibilitySuppressions.xml --------- Co-authored-by: Andreas Zerbst <andr317c@live.dk> Co-authored-by: Zeegaan <skrivdetud@gmail.com> Co-authored-by: Nikolaj Geisle <70372949+Zeegaan@users.noreply.github.com> # Conflicts: # tests/Umbraco.Tests.Integration/CompatibilitySuppressions.xml # tests/Umbraco.Tests.Integration/ManagementApi/ManagementApiTest.cs # tests/Umbraco.Tests.Integration/ManagementApi/Policies/AllCultureControllerTests.cs # tests/Umbraco.Tests.Integration/ManagementApi/Policies/CreateDocumentTests.cs # tests/Umbraco.Tests.Integration/ManagementApi/Policies/UpdateDocumentTests.cs # tests/Umbraco.Tests.Integration/ManagementApi/Preview/EndPreviewTests.cs # tests/Umbraco.Tests.Integration/ManagementApi/Preview/EnterPreviewTests.cs # tests/Umbraco.Tests.Integration/TestServerTest/UmbracoTestServerTestBase.cs * Updated test * Updates * Removed unnessecary test --------- Co-authored-by: Nhu Dinh <150406148+nhudinh0309@users.noreply.github.com> Co-authored-by: Zeegaan <skrivdetud@gmail.com> Co-authored-by: Nikolaj Geisle <70372949+Zeegaan@users.noreply.github.com>
2025-10-14 12:04:10 +02:00
public Task StartAsync(CancellationToken cancellationToken) => Task.CompletedTask;
V14: Add authorization policies to Management API controllers - p2 (#15211) * Making ProblemDetails details more generic * Adding authorizer that can be replaces for external authz in handlers. Adding handler and requirement for UserBelongsToUserGroupInRequest policy * Adding method to get the GUID from claims * Adding service methods to check user group authz * Porting MustSatisfyRequirementAuthorizationHandler * Adding controllers authz * Fix return status code + produced response type * Moving to folder * Adding DenyLocalLogin policy scaffold * Implement a temp DenyLocalLoginHandler * Introducing a new Fobidden result * Fix comment * Introducing a helper class for authorizers * Changed nullability for GetCurrentUser * Changes from Attempt to Status + FIXME comments * Create a UserGroupAuthorizationStatus to be used in the future * Introduces a new authz status for checking media acess * Introducing a new permission service for media * Adding fixme * Adding more policy configurations * Adding Media policy requirement and handler * Adding media authorizer * Fix order of params * Adding duplicate code comment * Adding authz to media controllers * Migrating more logic from MediaPermissions.cs * Adding more MediaAuthorizationStatus-es * Handling of new authorization status * Fix comment * Adding NotFound case * Adding NewDenyLocalLoginIfConfigured policy && commenting [AllowAnonymous] where the policy is applied since it is already handled * Changed Forbid() to Forbidden() to get the correct status code * Remove policy that is applied on the base controller already * Implement and apply NewUmbracoFeatureEnabled policy * Renaming classes to add Permission in the name * Register permission services * Add FIXME * Introduce new IUserGroupPermissionService and refactor accordingly * Add single overload with default implementation * Adding user permission policy and related * Applying admin policy * Register all new policies * Better wording * Add default implementation for a single overload * Adding remarks to IContentPermissionService.cs * Supporting null as key in ContentPermissionService * Fix namespace * Reverting back to not supporting null as content key, but having dedicated implementation * Adding content authorizer with null values to represent root item * Removing null key support and adding dedicated implementation * Removing remarks * Adding content resource with null support * Removing null support * Adding requirement and status * Adding content authorizer + handlers * Applying policies to content controllers * Update comment * Handling of Authorization Statuses * More authz in controllers * Fix comments * New branch handler * Obsolete old implementation * Adding dedicated policies to root and bin * Adding a branch specific namespace * Bin specific requirement and namespace * Root specific requirement and namespace * Changing to new root policy * Refactoring * Save policies * Fix null check/reference * Add TODO comment * Create media root- and bin-specific policies, handlers, etc. * Apply correct policy in create and update media controllers * Apply root policy to move and sort controllers * Fix wording * Adding UserGroupAuthorizationStatusResult * Remove all AuthorizationStatusResult as we cannot get the specific AuthorizationStatus * Fixing Umbraco feature policy * Fix allow anonymous endpoints - the value returned from DenyLocalLoginHandler wasn't enough, we need to succeed DenyAnonymousAuthorizationRequirement as it is required for some of the endpoints that had the attribute * Apply DenyLocalLoginIfConfigured policy to corresponding re-implementation of PostSetInvitedUserPassword * Fix comment * Renaming performingUser to user and fixing comments * Rename helper method * Fix references * Re-add merge conflict deletion * Adding Backoffice requirement and relevant * Registering * Added a simple policy test * Fixed small test things and clean up * Temp solution * Added one more test and fix another static issue * Fix another merge conflict * Remove BackOfficePermissionRequirement and handler as they might not be necessary * Comment out again [AllowAnonymous] * Remove AuthorizationPolicies.BackOfficeAccessWithoutApproval policy as it might not be necessary * Fix temp implementation * Fix reference to correct handler * Apply authz policy to new publish/unpublish controllers * Fix comments * Removing duplicate ProducesResponseTypes * Added swagger documentation about the 401 and 403 * Added Resources to Media, User and UserGroup * Handle root, recycle bin and branch in the same handler * Handle both parent and target when moving * Check Ids for all sort requests * Xml docs * Clean up * Clean up * Fix build * Cleanup * Remove TODO * Added missing overload * Use yield * Adding some keys to check --------- Co-authored-by: Bjarke Berg <mail@bergmania.dk> Co-authored-by: Andreas Zerbst <andr317c@live.dk>
2023-12-11 08:25:29 +01:00
public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
public Task StartedAsync(CancellationToken cancellationToken) => Task.CompletedTask;
public Task StartingAsync(CancellationToken cancellationToken)
{
_action();
return Task.CompletedTask;
}
Auhorization: Cherrypicked integration tests from V15 (#20492) * V15 QA Added the authorization integration tests (#18419) * Added authorization integration tests * Removed unnecessary tests and update tests for preview controller * Updated to use the newest changes from v15/dev and added an override for the AuthenticateClientAsync to use the userGroupKey * Updated CompatibilitySuppressions to include changes from integration tests * Updated pipelines * Skips managementApi tests * Only run necessary tests * Added new schema per fixture to reduce test setup time * Fixed failing tests * Updated test setup * Updated test * Added suppression * Fixed failing tests * Updated addOnTeardown methods to protected * Added method for clearing the host * Added teardown * Updated model usage * Added a lot of cleanup for memory leak issues when running tests * Added CompatibilitySuppressions.xml * Updated tests * Cleaned up * Adjusted base classes * Updated pipeline * Updated CompatibilitySuppressions.xml * Updated test logging * Fixed reponse * Updated condition to skip tests * Updated tests, not done * Reworked test to expect correct responses with correct setup * Updated tests * More updates to tests * Updated tests * Cleaned up tests * Updated setup * Cleaned up tests to match setup * Cleaned up setup * Removed suppression * Fixed tests * Move order of checks * Fix naming * Formatting * Dispose of host * Keep track of if we're disposed * Compat suppression * Dont dispose * Fix failing tests * removed unused virtual * Updated CompatibilitySuppressions.xml --------- Co-authored-by: Andreas Zerbst <andr317c@live.dk> Co-authored-by: Zeegaan <skrivdetud@gmail.com> Co-authored-by: Nikolaj Geisle <70372949+Zeegaan@users.noreply.github.com> # Conflicts: # tests/Umbraco.Tests.Integration/CompatibilitySuppressions.xml # tests/Umbraco.Tests.Integration/ManagementApi/ManagementApiTest.cs # tests/Umbraco.Tests.Integration/ManagementApi/Policies/AllCultureControllerTests.cs # tests/Umbraco.Tests.Integration/ManagementApi/Policies/CreateDocumentTests.cs # tests/Umbraco.Tests.Integration/ManagementApi/Policies/UpdateDocumentTests.cs # tests/Umbraco.Tests.Integration/ManagementApi/Preview/EndPreviewTests.cs # tests/Umbraco.Tests.Integration/ManagementApi/Preview/EnterPreviewTests.cs # tests/Umbraco.Tests.Integration/TestServerTest/UmbracoTestServerTestBase.cs * Updated test * Updates * Removed unnessecary test --------- Co-authored-by: Nhu Dinh <150406148+nhudinh0309@users.noreply.github.com> Co-authored-by: Zeegaan <skrivdetud@gmail.com> Co-authored-by: Nikolaj Geisle <70372949+Zeegaan@users.noreply.github.com>
2025-10-14 12:04:10 +02:00
V14: Add authorization policies to Management API controllers - p2 (#15211) * Making ProblemDetails details more generic * Adding authorizer that can be replaces for external authz in handlers. Adding handler and requirement for UserBelongsToUserGroupInRequest policy * Adding method to get the GUID from claims * Adding service methods to check user group authz * Porting MustSatisfyRequirementAuthorizationHandler * Adding controllers authz * Fix return status code + produced response type * Moving to folder * Adding DenyLocalLogin policy scaffold * Implement a temp DenyLocalLoginHandler * Introducing a new Fobidden result * Fix comment * Introducing a helper class for authorizers * Changed nullability for GetCurrentUser * Changes from Attempt to Status + FIXME comments * Create a UserGroupAuthorizationStatus to be used in the future * Introduces a new authz status for checking media acess * Introducing a new permission service for media * Adding fixme * Adding more policy configurations * Adding Media policy requirement and handler * Adding media authorizer * Fix order of params * Adding duplicate code comment * Adding authz to media controllers * Migrating more logic from MediaPermissions.cs * Adding more MediaAuthorizationStatus-es * Handling of new authorization status * Fix comment * Adding NotFound case * Adding NewDenyLocalLoginIfConfigured policy && commenting [AllowAnonymous] where the policy is applied since it is already handled * Changed Forbid() to Forbidden() to get the correct status code * Remove policy that is applied on the base controller already * Implement and apply NewUmbracoFeatureEnabled policy * Renaming classes to add Permission in the name * Register permission services * Add FIXME * Introduce new IUserGroupPermissionService and refactor accordingly * Add single overload with default implementation * Adding user permission policy and related * Applying admin policy * Register all new policies * Better wording * Add default implementation for a single overload * Adding remarks to IContentPermissionService.cs * Supporting null as key in ContentPermissionService * Fix namespace * Reverting back to not supporting null as content key, but having dedicated implementation * Adding content authorizer with null values to represent root item * Removing null key support and adding dedicated implementation * Removing remarks * Adding content resource with null support * Removing null support * Adding requirement and status * Adding content authorizer + handlers * Applying policies to content controllers * Update comment * Handling of Authorization Statuses * More authz in controllers * Fix comments * New branch handler * Obsolete old implementation * Adding dedicated policies to root and bin * Adding a branch specific namespace * Bin specific requirement and namespace * Root specific requirement and namespace * Changing to new root policy * Refactoring * Save policies * Fix null check/reference * Add TODO comment * Create media root- and bin-specific policies, handlers, etc. * Apply correct policy in create and update media controllers * Apply root policy to move and sort controllers * Fix wording * Adding UserGroupAuthorizationStatusResult * Remove all AuthorizationStatusResult as we cannot get the specific AuthorizationStatus * Fixing Umbraco feature policy * Fix allow anonymous endpoints - the value returned from DenyLocalLoginHandler wasn't enough, we need to succeed DenyAnonymousAuthorizationRequirement as it is required for some of the endpoints that had the attribute * Apply DenyLocalLoginIfConfigured policy to corresponding re-implementation of PostSetInvitedUserPassword * Fix comment * Renaming performingUser to user and fixing comments * Rename helper method * Fix references * Re-add merge conflict deletion * Adding Backoffice requirement and relevant * Registering * Added a simple policy test * Fixed small test things and clean up * Temp solution * Added one more test and fix another static issue * Fix another merge conflict * Remove BackOfficePermissionRequirement and handler as they might not be necessary * Comment out again [AllowAnonymous] * Remove AuthorizationPolicies.BackOfficeAccessWithoutApproval policy as it might not be necessary * Fix temp implementation * Fix reference to correct handler * Apply authz policy to new publish/unpublish controllers * Fix comments * Removing duplicate ProducesResponseTypes * Added swagger documentation about the 401 and 403 * Added Resources to Media, User and UserGroup * Handle root, recycle bin and branch in the same handler * Handle both parent and target when moving * Check Ids for all sort requests * Xml docs * Clean up * Clean up * Fix build * Cleanup * Remove TODO * Added missing overload * Use yield * Adding some keys to check --------- Co-authored-by: Bjarke Berg <mail@bergmania.dk> Co-authored-by: Andreas Zerbst <andr317c@live.dk>
2023-12-11 08:25:29 +01:00
public Task StoppedAsync(CancellationToken cancellationToken) => Task.CompletedTask;
public Task StoppingAsync(CancellationToken cancellationToken) => Task.CompletedTask;
}