57f5239cfc
The "Auto-elevate ownership when permission scan is denied" setting was dead code: the toggle was persisted but never read, the audit flow never passed its onAccessDenied callback, and EnrichException wrapped every CSOM error (including ServerUnauthorizedAccessException) into a generic InvalidOperationException so the access-denied catch could never match. Centralize elevation instead of per-call-site callbacks: - Throw typed SharePointAccessDeniedException from EnrichException on access-denied, preserving the failing site URL and enriched diagnostic. - Add scoped IElevationCoordinator that catches it, and when AutoTakeOwnership is enabled takes site-collection admin via the tenant admin endpoint and retries the operation once. Per-site dedupe prevents loops; admin-host denials are not treated as ownership issues. Retry is safe because each wrapped operation closure re-issues its own CSOM loads. - Wrap all site-scoped operations (Storage, Permissions, Duplicates, Search, VersionCleanup, FolderStructure, BulkMembers, FileTransfer, Templates) and the UserAccessAudit per-site scan in the coordinator. - Drop the unused onAccessDenied parameter from IUserAccessAuditService. Elevation still requires SharePoint tenant admin rights on the signed-in account; the coordinator surfaces a clear message when that is missing. Also keeps the prior StorageService change that avoids admin-gated folder.StorageMetrics (403 for delegated non-admin tokens). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
115 lines
4.5 KiB
C#
115 lines
4.5 KiB
C#
using SharepointToolbox.Web.Core.Helpers;
|
|
using SharepointToolbox.Web.Core.Models;
|
|
|
|
namespace SharepointToolbox.Web.Services;
|
|
|
|
public class UserAccessAuditService : IUserAccessAuditService
|
|
{
|
|
private readonly IPermissionsService _permissionsService;
|
|
private readonly IElevationCoordinator _elevation;
|
|
|
|
private static readonly HashSet<string> HighPrivilegeLevels = new(StringComparer.OrdinalIgnoreCase)
|
|
{
|
|
"Full Control", "Site Collection Administrator"
|
|
};
|
|
|
|
public UserAccessAuditService(IPermissionsService permissionsService, IElevationCoordinator elevation)
|
|
{
|
|
_permissionsService = permissionsService;
|
|
_elevation = elevation;
|
|
}
|
|
|
|
public async Task<IReadOnlyList<UserAccessEntry>> AuditUsersAsync(
|
|
ISessionManager sessionManager,
|
|
TenantProfile currentProfile,
|
|
IReadOnlyList<string> targetUserLogins,
|
|
IReadOnlyList<SiteInfo> sites,
|
|
ScanOptions options,
|
|
IProgress<OperationProgress> progress,
|
|
CancellationToken ct)
|
|
{
|
|
var targets = targetUserLogins
|
|
.Select(l => l.Trim().ToLowerInvariant())
|
|
.Where(l => l.Length > 0).ToHashSet();
|
|
|
|
if (targets.Count == 0) return Array.Empty<UserAccessEntry>();
|
|
|
|
var allEntries = new List<UserAccessEntry>();
|
|
|
|
for (int i = 0; i < sites.Count; i++)
|
|
{
|
|
ct.ThrowIfCancellationRequested();
|
|
var site = sites[i];
|
|
progress.Report(new OperationProgress(i, sites.Count,
|
|
$"Scanning site {i + 1}/{sites.Count}: {site.Title}..."));
|
|
|
|
var profile = new TenantProfile
|
|
{
|
|
TenantUrl = site.Url,
|
|
TenantId = currentProfile.TenantId,
|
|
ClientId = currentProfile.ClientId,
|
|
Name = site.Title
|
|
};
|
|
|
|
// Auto-elevates site-collection admin ownership and retries when a scan is denied,
|
|
// if the AutoTakeOwnership setting is enabled (otherwise the access-denied propagates).
|
|
var permEntries = await _elevation.RunAsync(async c =>
|
|
{
|
|
var ctx = await sessionManager.GetOrCreateContextAsync(profile, c);
|
|
return await _permissionsService.ScanSiteAsync(ctx, options, progress, c);
|
|
}, ct);
|
|
|
|
allEntries.AddRange(TransformEntries(permEntries, targets, site));
|
|
}
|
|
|
|
progress.Report(new OperationProgress(sites.Count, sites.Count,
|
|
$"Audit complete: {allEntries.Count} access entries found."));
|
|
return allEntries;
|
|
}
|
|
|
|
private static IEnumerable<UserAccessEntry> TransformEntries(
|
|
IReadOnlyList<PermissionEntry> permEntries, HashSet<string> targets, SiteInfo site)
|
|
{
|
|
foreach (var entry in permEntries)
|
|
{
|
|
var logins = entry.UserLogins.Split(';', StringSplitOptions.RemoveEmptyEntries);
|
|
var names = entry.Users.Split(';', StringSplitOptions.RemoveEmptyEntries);
|
|
var permLevels = entry.PermissionLevels.Split(';', StringSplitOptions.RemoveEmptyEntries);
|
|
|
|
for (int u = 0; u < logins.Length; u++)
|
|
{
|
|
var login = logins[u].Trim();
|
|
var loginLower = login.ToLowerInvariant();
|
|
var displayName = u < names.Length ? names[u].Trim() : login;
|
|
|
|
bool isTarget = targets.Any(t => loginLower.Contains(t) || t.Contains(loginLower));
|
|
if (!isTarget) continue;
|
|
|
|
var accessType = !entry.HasUniquePermissions ? AccessType.Inherited
|
|
: entry.GrantedThrough.StartsWith("SharePoint Group:", StringComparison.OrdinalIgnoreCase)
|
|
? AccessType.Group : AccessType.Direct;
|
|
|
|
foreach (var level in permLevels)
|
|
{
|
|
var trimmed = level.Trim();
|
|
if (string.IsNullOrEmpty(trimmed)) continue;
|
|
yield return new UserAccessEntry(
|
|
displayName, StripClaimsPrefix(login),
|
|
site.Url, site.Title,
|
|
entry.ObjectType, entry.Title, entry.Url,
|
|
trimmed, accessType, entry.GrantedThrough,
|
|
HighPrivilegeLevels.Contains(trimmed),
|
|
PermissionEntryHelper.IsExternalUser(login),
|
|
entry.TargetUrl, entry.TargetLabel, entry.SharingLinkType);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
private static string StripClaimsPrefix(string login)
|
|
{
|
|
int pipe = login.LastIndexOf('|');
|
|
return pipe >= 0 ? login[(pipe + 1)..] : login;
|
|
}
|
|
}
|