diff --git a/DI/XDIHelperExtension.cs b/DI/XDIHelperExtension.cs index 2c19e6d..976bd36 100644 --- a/DI/XDIHelperExtension.cs +++ b/DI/XDIHelperExtension.cs @@ -14,12 +14,13 @@ using xMessageService.DI; using xStorageService.DI; using xCommons.Extensions; using xIds.Configurations; -using xIdentityService.DI; using xExceptions.Constants; using xCommons.Authorization; using System.Collections.Generic; using xMessageService.Interfaces; using xStorageService.Interfaces; +using xIdentityService.Providers; +using xIdentityService.Extensions; using xIdentityService.Interfaces; using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.Logging; @@ -95,6 +96,10 @@ namespace xIds.DI source.AddScoped(); source.AddScoped(); + // + source.AddXAuthorizationCache(); + source.AddScoped(); + // source.AddXAuthorizationProvider(); } diff --git a/Extensions/IdentityExtensions.cs b/Extensions/IdentityExtensions.cs index 6f01dec..35aea6e 100644 --- a/Extensions/IdentityExtensions.cs +++ b/Extensions/IdentityExtensions.cs @@ -1,5 +1,8 @@ using xIds.Providers; using xIds.Interfaces; +using xCommons.Extensions; +using xExceptions.Constants; +using xIdentityService.Interfaces; using Microsoft.Extensions.DependencyInjection; namespace xIds.Extensions @@ -25,5 +28,37 @@ namespace xIds.Extensions { source.AddScoped(); } + + /// + /// Register Authorization Provider ... + /// + /// + public static void AddXAuthorizationProvider( + this IServiceCollection source + ) + { + // + // Validate Requirements ... + var roles = source.GetRegisteredService(); + var scopes = source.GetRegisteredService(); + var policies = source.GetRegisteredService(); + var cache = source.GetRegisteredService(); + var resolver = source.GetRegisteredService(); + + // + var isInvalid = + roles.IsNull() || + cache.IsNull() || + scopes.IsNull() || + policies.IsNull() || + resolver.IsNull(); + if (isInvalid) + { + XException.InvalidConfiguration.Throw(); + } + + // + source.AddScoped(); + } } } \ No newline at end of file diff --git a/Providers/XAuthorizationProvider.cs b/Providers/XAuthorizationProvider.cs index 9e522b6..7910e59 100644 --- a/Providers/XAuthorizationProvider.cs +++ b/Providers/XAuthorizationProvider.cs @@ -6,11 +6,14 @@ using xCommons.Extensions; using xIdentityModels.Dtos; using xExceptions.Constants; using System.Threading.Tasks; +using xIdentityModels.Models; using xIdentityService.Models; +using xIdentityModels.Constants; using System.Collections.Generic; using IdentityServer4.Extensions; using xIdentityService.Interfaces; using xIdentityService.Extensions; +using Microsoft.AspNetCore.Authorization; namespace xIds.Providers { @@ -41,12 +44,14 @@ namespace xIds.Providers this.policies = policies; this.resolver = resolver; } - + // #region Commons ... /// /// Clear Local Cache and Notify other Instances ... /// + /// + /// public async Task InvalidateAsync(string policyName = null) { // @@ -59,10 +64,193 @@ namespace xIds.Providers cache.RemovePolicy(policyName); } } + + /// + /// Build Authorization Policy ... + /// + /// + /// + /// + public async Task BuildAuthorizationPolicyAsync( + string policyName, + CancellationToken cancellationToken = default + ) + { + // + var effective = await GetEffectiveAuthorizationAsync(policyName, cancellationToken); + + // + var result = effective.ToAuthorizationPolicy(); + return result; + } + + /// + /// Get Effective Authorization ... + /// + /// + /// + /// + public async Task GetEffectiveAuthorizationAsync( + XUserClaimsInfoDto target, + CancellationToken cancellationToken = default + ) + { + // + // Define Result ... + var result = new XEffectiveAuthorizationDto + { + EffectiveClaims = [], + RequireEnabledUser = !target.IsNull(), + RequireAuthenticatedUser = !target.IsNull(), + EffectiveRoles = new HashSet(StringComparer.OrdinalIgnoreCase), + EffectiveScopes = new HashSet(StringComparer.OrdinalIgnoreCase), + }; + + // + // Validate ... + if (target.IsNull()) + { + return result; + } + + // + // Effective roles = the user's actual roles (from RoleManager) ... + var userRoles = await GetUserRolesAsync( + cancellationToken: cancellationToken, + userId: target.GetUserSelectByParam(userSelectBy: XUserSelectBy.ID) + ); + foreach (var role in userRoles) + { + result.EffectiveRoles.Add(role); + } + + // + // NOTE: EffectiveScopes / EffectiveClaims aggregation is wired here from + // the user's scope / claim source on XUserClaimsInfoDto (xIdentityModels). + return result; + } + + /// + /// Get Effective Authorization ... + /// + /// + /// + /// + public async Task GetEffectiveAuthorizationAsync( + string policyName, + CancellationToken cancellationToken = default + ) + { + // + if (policyName.IsNullOrEmpty()) + { + XException.InvalidArgs.Throw(); + } + + // + var policy = await FindPolicyOrThrowAsync(policyName, cancellationToken); + var effective = await ToDtoWithEffectiveRolesAsync(policy, cancellationToken); + if (effective.IsNull()) + { + XException.InvalidConfiguration.Throw(); + } + + // + return effective; + } #endregion // #region Private ... + private async Task ValidateReferencesAsync( + XPolicyDefinitionDto item, + CancellationToken cancellationToken + ) + { + // + // Defensive guard ... + if (item.IsNull()) + { + XException.InvalidArgs.Throw(); + } + + // + // The DTO stores RequiredRoles / RequiredScopes as CSV strings. + // Parse them into collections ONCE (ParseListString NREs on a null + // string, so guard first) ... + + // + var requiredRoles = item.RequiredRoles.IsNullOrEmpty() + ? [] + : item.RequiredRoles.ParseListString().ToList(); + + // + var requiredScopes = item.RequiredScopes.IsNullOrEmpty() + ? [] + : item.RequiredScopes.ParseListString().ToList(); + + // + // Referenced Roles must exist ... + if (requiredRoles.HasChild()) + { + // + var existingRoles = new HashSet( + (await roles.GetAllAsync(cancellationToken: cancellationToken)) + .Select(r => r.Name.ToNormalString()), + StringComparer.OrdinalIgnoreCase + ); + if (requiredRoles.Any(r => !existingRoles.Contains(r.ToNormalString()))) + { + XException.NotFound.Throw(); + } + } + + // + // Referenced Scopes must exist ... + if (requiredScopes.HasChild()) + { + // + var existingScopes = new HashSet( + (await scopes.GetAllAsync(cancellationToken: cancellationToken)) + .Select(s => s.Name.ToNormalString()), + StringComparer.OrdinalIgnoreCase + ); + if (requiredScopes.Any(s => !existingScopes.Contains(s.ToNormalString()))) + { + XException.NotFound.Throw(); + } + } + } + + public async Task> GetUserRolesAsync( + string userId, + CancellationToken cancellationToken = default + ) + { + // + if (userId.IsNullOrEmpty()) + { + XException.InvalidArgs.Throw(); + } + + // + cancellationToken.ThrowIfCancellationRequested(); + + // + var user = await manager.UserManager.FindByIdAsync(userId); + if (user.IsNull()) + { + XException.NotFound.Throw(); + } + + // + cancellationToken.ThrowIfCancellationRequested(); + + // + var result = await manager.UserManager.GetRolesAsync(user); + return result; + } + private async Task FindRoleOrThrowAsync( string name, CancellationToken cancellationToken @@ -141,66 +329,6 @@ namespace xIds.Providers return result; } - private async Task ValidateReferencesAsync( - XPolicyDefinitionDto item, - CancellationToken cancellationToken - ) - { - // - // Defensive guard ... - if (item.IsNull()) - { - XException.InvalidArgs.Throw(); - } - - // - // The DTO stores RequiredRoles / RequiredScopes as CSV strings. - // Parse them into collections ONCE (ParseListString NREs on a null - // string, so guard first) ... - - // - var requiredRoles = item.RequiredRoles.IsNullOrEmpty() - ? [] - : item.RequiredRoles.ParseListString().ToList(); - - // - var requiredScopes = item.RequiredScopes.IsNullOrEmpty() - ? [] - : item.RequiredScopes.ParseListString().ToList(); - - // - // Referenced Roles must exist ... - if (requiredRoles.HasChild()) - { - // - var existingRoles = new HashSet( - (await roles.GetAllAsync(cancellationToken: cancellationToken)) - .Select(r => r.Name.ToNormalString()), - StringComparer.OrdinalIgnoreCase - ); - if (requiredRoles.Any(r => !existingRoles.Contains(r.ToNormalString()))) - { - XException.NotFound.Throw(); - } - } - - // - // Referenced Scopes must exist ... - if (requiredScopes.HasChild()) - { - // - var existingScopes = new HashSet( - (await scopes.GetAllAsync(cancellationToken: cancellationToken)) - .Select(s => s.Name.ToNormalString()), - StringComparer.OrdinalIgnoreCase - ); - if (requiredScopes.Any(s => !existingScopes.Contains(s.ToNormalString()))) - { - XException.NotFound.Throw(); - } - } - } - private async Task ToDtoWithEffectiveRolesAsync( XPolicyDefinitionDto item, CancellationToken cancellationToken = default diff --git a/Providers/XAuthorizationProvider/XAuthorizationProvider+Policy.cs b/Providers/XAuthorizationProvider/XAuthorizationProvider+Policy.cs new file mode 100644 index 0000000..d5646bf --- /dev/null +++ b/Providers/XAuthorizationProvider/XAuthorizationProvider+Policy.cs @@ -0,0 +1,250 @@ +using xModels.Dtos; +using System.Threading; +using xCommons.Extensions; +using xIdentityModels.Dtos; +using xExceptions.Constants; +using xIdentityModels.Models; +using System.Threading.Tasks; +using xIdentityService.Models; +using System.Collections.Generic; + +namespace xIds.Providers +{ + public partial class XAuthorizationProvider + { + // + #region Policy ... + public async Task RemovePolicyAsync( + string name, + XUserClaimsInfoDto userInfo, + CancellationToken cancellationToken = default + ) + { + // + var existing = await FindPolicyOrThrowAsync(name, cancellationToken); + if (existing.IsSystem) + { + XException.NotAllowed.Throw(); + } + + // + await policies.RemoveAsync( + id: existing.Id, + userInfo: userInfo, + cancellationToken: cancellationToken + ); + + // + await InvalidateAsync(existing.Name); + return true; + } + + public async Task GetPolicyAsync( + string name, + CancellationToken cancellationToken = default + ) + { + // + var result = await FindPolicyOrThrowAsync(name, cancellationToken); + + // + return result; + } + + public async Task AddPolicyAsync( + XPolicyDefinitionDto item, + XUserClaimsInfoDto userInfo, + CancellationToken cancellationToken = default + ) + { + // + if (item.IsNull() || item.Name.IsNullOrEmpty()) + { + XException.InvalidArgs.Throw(); + } + + // + var normalized = item.Name.ToNormalString(); + var exists = await policies.FindOneAsync( + predicate: p => p.Name.ToLower() == normalized, + cancellationToken: cancellationToken + ); + if (!exists.IsNull()) + { + XException.Duplicate.Throw(); + } + + // + // ⚠️ CRITICAL: مقصد همه Role/Scopeها وجود داشته باشند + await ValidateReferencesAsync(item, cancellationToken); + + // + item.IsSystem = false; + var result = await policies.AddAsync( + item: item, + userInfo: userInfo, + cancellationToken: cancellationToken + ); + + // + await InvalidateAsync(); + return result; + } + + public async Task UpdatePolicyAsync( + string name, + XPolicyDefinitionDto item, + XUserClaimsInfoDto userInfo, + CancellationToken cancellationToken = default + ) + { + // + if (name.IsNullOrEmpty() || item.IsNull()) + { + XException.InvalidArgs.Throw(); + } + + // + var existing = await FindPolicyOrThrowAsync(name, cancellationToken); + if (existing.IsSystem) + { + XException.NotAllowed.Throw(); + } + + // + // Reference validation BEFORE update — same as Add + await ValidateReferencesAsync(item, cancellationToken); + + // + var updated = await policies.UpdateAsync( + id: existing.Id, + item: item, + userInfo: userInfo, + cancellationToken: cancellationToken + ); + + // + await InvalidateAsync(existing.Name); + return updated; + } + + public async Task EvaluatePolicyAsync( + string name, + XUserClaimsInfoDto target, + CancellationToken cancellationToken = default + ) + { + // + // Load the policy (throws NotFound when missing) ... + var dto = await FindPolicyOrThrowAsync(name, cancellationToken); + + // + var result = new XPolicyEvaluationResultDto + { + Passed = true, + Policy = dto.Name, + FailedRequirements = [] + }; + + // + // Build the policy's effective authorization via the shared helper + // (resolver + projection onto XEffectiveAuthorizationDto) ... + var auth = await ToDtoWithEffectiveRolesAsync(dto, cancellationToken); + if (auth.IsNull()) + { + // + result.Passed = false; + result.FailedRequirements.Add("PolicyNotBuilt"); + + // + return result; + } + + // + // Anonymous user fails any policy that requires authentication ... + if (target.IsNull()) + { + // + if (auth.RequireAuthenticatedUser) + { + // + result.Passed = false; + result.FailedRequirements.Add("RequireAuthenticatedUser"); + } + + // + return result; + } + + // + // Effective Roles: the user must hold at least one ... + if (auth.EffectiveRoles.HasChild()) + { + // // + // var userSelectByParam = target.GetUserSelectByParam(); + + // // + // var userRoles = await roles.FindManyAsync( + // predicate: x => x. + // cancellationToken: cancellationToken + // ); + + // // + // var matched = auth.EffectiveRoles.Any(er => + // userRoles.Any(ur => + // string.Equals(ur, er, StringComparison.OrdinalIgnoreCase) + // ) + // ); + + // + // if (!matched) + // { + // // + // result.Passed = false; + // result.FailedRequirements.Add("RequiredRoles"); + // } + } + + // + // NOTE: RequireEnabledUser (IsEnabled / !IsBanned), EffectiveScopes and + // EffectiveClaims checks are layered on here once the matching flags / + // collections on XUserClaimsInfoDto (xIdentityModels) are wired. + return result; + } + + public async Task> GetPoliciesAsync( + CancellationToken cancellationToken = default + ) + { + // + var result = await policies + .GetAllAsync(cancellationToken: cancellationToken); + + // + return result; + } + + public async Task> QueryPoliciesAsync( + XQuery query, + CancellationToken cancellationToken = default + ) + { + // + // Validate ... + if (query.IsNull()) + { + XException.InvalidArgs.Throw(); + } + + // + var result = await policies.QueryAsync( + query: query, + cancellationToken: cancellationToken + ); + + // + return result; + } + #endregion + } +} \ No newline at end of file diff --git a/Providers/XAuthorizationProvider/XAuthorizationProvider+Role.cs b/Providers/XAuthorizationProvider/XAuthorizationProvider+Role.cs index 0d453d9..6e2348d 100644 --- a/Providers/XAuthorizationProvider/XAuthorizationProvider+Role.cs +++ b/Providers/XAuthorizationProvider/XAuthorizationProvider+Role.cs @@ -1,11 +1,13 @@ using System; using System.Linq; +using xModels.Dtos; using System.Threading; using xCommons.Extensions; using xIdentityModels.Dtos; using xExceptions.Constants; using System.Threading.Tasks; using xIdentityModels.Models; +using System.Collections.Generic; namespace xIds.Providers { @@ -13,6 +15,74 @@ namespace xIds.Providers { // #region Role ... + public async Task RemoveRoleAsync( + string name, + XUserClaimsInfoDto userInfo, + CancellationToken cancellationToken = default + ) + { + // + var existing = await FindRoleOrThrowAsync(name, cancellationToken); + if (existing.IsSystem) + { + XException.NotAllowed.Throw(); + } + + // + // ⚠️ CRITICAL: capture affected users BEFORE delete. + // After DeleteRoleAsync, AspNetUserRoles rows are gone. + var affectedUsers = await manager.UserManager.GetUsersInRoleAsync(existing.Name); + var affectedUserIds = affectedUsers.Select(u => u.Id).ToList(); + + // + // Delete from local DB + await roles.RemoveAsync( + id: existing.Id, + userInfo: userInfo, + cancellationToken: cancellationToken + ); + + // + // Delete from IdentityServer — this cascades AspNetUserRoles + await manager.DeleteRoleAsync(existing.Name, cancellationToken); + + // + await InvalidateAsync(); + return true; + } + + public async Task CountUsersInRoleAsync( + string name, + CancellationToken cancellationToken = default + ) + { + // + // Fail fast if the role itself does not exist ... + await FindRoleOrThrowAsync(name, cancellationToken); + + // + var usersInRole = await manager + .UserManager.GetUsersInRoleAsync(name); + + // + var result = usersInRole.Count(); + + // + return result; + } + + public async Task GetRoleAsync( + string name, + CancellationToken cancellationToken = default + ) + { + // + var result = await FindRoleOrThrowAsync(name, cancellationToken); + + // + return result; + } + public async Task AddRoleAsync( XRoleDefinitionDto item, XUserClaimsInfoDto userInfo, @@ -73,7 +143,7 @@ namespace xIds.Providers } public async Task UpdateRoleAsync( - string name, + string name, XRoleDefinitionDto item, XUserClaimsInfoDto userInfo, CancellationToken cancellationToken = default @@ -126,7 +196,7 @@ namespace xIds.Providers } // - foreach(var user in usersInRole) + foreach (var user in usersInRole) { // await manager.AddUserToRoleAsync( @@ -141,41 +211,39 @@ namespace xIds.Providers return updated; } - public async Task RemoveRoleAsync( - string name, - XUserClaimsInfoDto userInfo, + public async Task> GetRolesAsync( CancellationToken cancellationToken = default ) { // - var existing = await FindRoleOrThrowAsync(name, cancellationToken); - if (existing.IsSystem) + var result = await roles + .GetAllAsync(cancellationToken: cancellationToken); + + // + return result; + } + + public async Task> QueryRolesAsync( + XQuery query, + CancellationToken cancellationToken = default + ) + { + // + // Validate ... + if (query.IsNull()) { - XException.NotAllowed.Throw(); + XException.InvalidArgs.Throw(); } // - // ⚠️ CRITICAL: capture affected users BEFORE delete. - // After DeleteRoleAsync, AspNetUserRoles rows are gone. - var affectedUsers = await manager.UserManager.GetUsersInRoleAsync(existing.Name); - var affectedUserIds = affectedUsers.Select(u => u.Id).ToList(); - - // - // Delete from local DB - await roles.RemoveAsync( - id: existing.Id, - userInfo: userInfo, + var result = await roles.QueryAsync( + query: query, cancellationToken: cancellationToken ); // - // Delete from IdentityServer — this cascades AspNetUserRoles - await manager.DeleteRoleAsync(existing.Name, cancellationToken); - - // - await InvalidateAsync(); - return true; - } + return result; + } #endregion } } \ No newline at end of file diff --git a/Providers/XAuthorizationProvider/XAuthorizationProvider+Scope.cs b/Providers/XAuthorizationProvider/XAuthorizationProvider+Scope.cs index 856ac68..ae6d1fb 100644 --- a/Providers/XAuthorizationProvider/XAuthorizationProvider+Scope.cs +++ b/Providers/XAuthorizationProvider/XAuthorizationProvider+Scope.cs @@ -1,5 +1,6 @@ using System; using System.Linq; +using xModels.Dtos; using System.Threading; using xCommons.Extensions; using xIdentityModels.Dtos; @@ -14,12 +15,36 @@ namespace xIds.Providers { // #region Scope ... - public async Task> GetScopesAsync( + public async Task RemoveScopeAsync( + string name, + XUserClaimsInfoDto userInfo, CancellationToken cancellationToken = default ) { - return await scopes - .GetAllAsync(cancellationToken: cancellationToken); + // + var existing = await FindScopeOrThrowAsync(name, cancellationToken); + if (existing.IsSystem) { + XException.NotAllowed.Throw(); + } + + // + var affectedPolicies = (await policies.GetAllAsync(cancellationToken: cancellationToken)) + .Where(p => !p.RequiredScopes.IsNullOrEmpty() + && p.RequiredScopes.ParseListString() + .Any(s => string.Equals(s, existing.Name, + StringComparison.OrdinalIgnoreCase))) + .ToList(); + + // + await scopes.RemoveAsync( + id: existing.Id, + userInfo: userInfo, + cancellationToken: cancellationToken + ); + + // + await InvalidateAsync(); + return true; } public async Task GetScopeAsync( @@ -97,38 +122,35 @@ namespace xIds.Providers await InvalidateAsync(); return updated; } + + public async Task> GetScopesAsync( + CancellationToken cancellationToken = default + ) + { + return await scopes + .GetAllAsync(cancellationToken: cancellationToken); + } - public async Task RemoveScopeAsync( - string name, - XUserClaimsInfoDto userInfo, + public async Task> QueryScopesAsync( + XQuery query, CancellationToken cancellationToken = default ) { // - var existing = await FindScopeOrThrowAsync(name, cancellationToken); - if (existing.IsSystem) { - XException.NotAllowed.Throw(); + if (query.IsNull()) + { + XException.InvalidArgs.Throw(); } // - var affectedPolicies = (await policies.GetAllAsync(cancellationToken: cancellationToken)) - .Where(p => !p.RequiredScopes.IsNullOrEmpty() - && p.RequiredScopes.ParseListString() - .Any(s => string.Equals(s, existing.Name, - StringComparison.OrdinalIgnoreCase))) - .ToList(); - - // - await scopes.RemoveAsync( - id: existing.Id, - userInfo: userInfo, + var result = await scopes.QueryAsync( + query: query, cancellationToken: cancellationToken ); - + // - await InvalidateAsync(); - return true; - } + return result; + } #endregion } } \ No newline at end of file