Files
kawa 6d9c79ad5a Add scheduled reports + app-only cert auth; fix tenant-wide user-access audit
Feature work:
- Certificate (app-only) auth per profile: cert store, context/Graph client
  factories, automated app-registration provisioning (delegated + application
  permissions, admin consent), and a SessionManager seam that resolves the auth
  model per profile.
- Scheduled reports: repositories, hosted service/runner/coordinator, report
  pages, and email delivery (app-only Mail.Send).
- Tenant-wide user-access audit when no site is selected.

Audit fixes:
- Site enumeration: app-only discovery used Graph getAllSites (needs Graph
  Sites.Read.All the cert app lacks) and silently returned empty. Switched to
  the admin-host CSOM TenantSiteEnumerator, matching the scheduler; both auth
  models now share one enumeration path.
- Group expansion: the scan records a SharePoint group as a single principal, so
  user-centric audits found nothing for group-granted access. Resolve group
  membership (shared by audit + scheduler) and attribute it to the target user.
- M365 group claims: the resolver only recognized AAD security groups
  (c:0t.c|). Group-connected/Teams sites grant via the M365 group claim
  (c:0o.c|…|<guid>[_o]); now expanded too, resolving owners for the "_o" claim.
- Provision Directory.Read.All as an application permission so M365/AAD group
  expansion works under the cert identity.

Also: ignore data/appcerts/ (encrypted certificate key material).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 17:55:28 +02:00

277 lines
16 KiB
Plaintext

@page "/user-audit"
@attribute [Authorize]
@inject IUserSessionService Session
@inject ISessionManager SessionMgr
@inject IUserAccessAuditService AuditSvc
@inject IGraphUserDirectoryService GraphSvc
@inject ISiteDiscoveryService SiteDiscovery
@inject UserAccessCsvExportService CsvExport
@inject UserAccessHtmlExportService HtmlExport
@inject WebExportService WebExport
@inject IAuditService Audit
@inject TranslationSource T
@rendermode InteractiveServer
<h1 class="page-title">@T["tab.userAccessAudit"]</h1>
<p class="page-subtitle">@T["audit.subtitle"]</p>
@if (!Session.HasProfile) { <NoProfilePrompt /> return; }
<div class="card">
<div class="form-group">
<div class="flex-row">
<label class="form-label" style="margin:0">@T["audit.lbl.users"]</label>
<div class="spacer"></div>
<label style="font-weight:normal"><input type="checkbox" @bind="_includeGuests" /> @T["directory.chk.guests"]<HelpTip Text="@T["help.guests"]" Wide="true" /></label>
<button class="btn btn-secondary btn-sm" @onclick="LoadUsers" disabled="@_loadingUsers">
@(_loadingUsers ? string.Format(T["audit.btn.loading"], _loadCount) : T["audit.btn.loadUsers"])
</button>
</div>
@if (_directoryUsers.Count > 0)
{
<div class="flex-row mt-8">
<input class="form-input" style="width:260px" @bind="_userFilter" @bind:event="oninput" placeholder="@T["audit.ph.filterUsers"]" />
<span class="text-muted">@string.Format(T["audit.lbl.selectedCount"], _selectedEmails.Count)</span>
<div class="spacer"></div>
<button class="btn btn-link btn-sm" @onclick="SelectAllFiltered">@string.Format(T["audit.btn.selectAll"], FilteredUsers.Count())</button>
<button class="btn btn-link btn-sm" @onclick="ClearSelection">@T["settings.logo.clear"]</button>
</div>
<div class="user-select-list">
@foreach (var u in FilteredUsers.Take(500))
{
var email = u.Mail ?? u.UserPrincipalName;
<label class="user-select-row">
<input type="checkbox" checked="@_selectedEmails.Contains(email)"
@onchange="e => ToggleUser(email, (bool)e.Value!)" />
<span class="user-select-name">@u.DisplayName</span>
<span class="text-muted">@email</span>
@if (u.UserType == "Guest") { <span class="chip chip-yellow">@T["common.guest"]</span> }
</label>
}
</div>
@if (FilteredUsers.Count() > 500) { <div class="text-muted mt-8">@T["audit.msg.showFirst500Filter"]</div> }
}
<label class="form-label mt-8">@T["audit.lbl.additionalEmails"]</label>
<textarea class="form-textarea" @bind="_users" placeholder="alice@contoso.com&#10;bob@contoso.com" rows="2"></textarea>
</div>
<SitePicker Profile="Session.CurrentProfile!" @bind-SelectedSites="_sites" />
<div class="text-muted" style="margin-top:4px">@T["audit.hint.allSites"]</div>
<div class="form-row">
<div class="form-group" style="display:flex;align-items:center;gap:16px;padding-top:20px">
<label><input type="checkbox" @bind="_includeInherited" /> @T["audit.chk.includeInherited"]<HelpTip Text="@T["help.inheritedPerms"]" /></label>
<label><input type="checkbox" @bind="_scanFolders" /> @T["chk.scan.folders"]</label>
<label><input type="checkbox" @bind="_includeSubsites" /> @T["chk.include.subsites"]<HelpTip Text="@T["help.subsites"]" /></label>
</div>
</div>
<div class="flex-row mt-8">
<button class="btn btn-primary" @onclick="RunAudit" disabled="@_running">
@(_running ? T["audit.btn.auditing"] : T["audit.btn.auditUsers"])
</button>
@if (_running) { <button class="btn btn-secondary" @onclick="Cancel">@T["btn.cancel"]</button> }
</div>
<ProgressPanel IsRunning="_running" StatusMessage="@_status" Current="_current" Total="_total" />
</div>
@if (!string.IsNullOrEmpty(_error)) { <div class="alert alert-error">@_error</div> }
@if (_results.Count > 0)
{
<div class="card">
<div class="flex-row">
<div class="card-title">@T["audit.results.title"] <span class="count-badge">@_results.Count</span></div>
<button class="btn btn-sm @(_viewMode == "site" ? "btn-primary" : "btn-secondary")" @onclick='() => _viewMode = "site"'>@T["audit.view.bySite"]</button>
<button class="btn btn-sm @(_viewMode == "flat" ? "btn-primary" : "btn-secondary")" @onclick='() => _viewMode = "flat"'>@T["audit.view.table"]</button>
<div class="spacer"></div>
<button class="btn btn-secondary btn-sm" @onclick="ExportCsv">@T["audit.btn.exportCsv"]</button>
<button class="btn btn-secondary btn-sm" @onclick="ExportHtml">@T["audit.btn.exportHtml"]</button>
</div>
@if (_sitesScanned > 0)
{
<div class="flex-row mt-8" style="gap:8px">
<span class="chip chip-blue">@string.Format(T["audit.scan.sitesScanned"], _sitesScanned)</span>
@if (_sitesDenied > 0) { <span class="chip chip-yellow">@string.Format(T["audit.scan.sitesDenied"], _sitesDenied)</span> }
@if (_sitesFailed > 0) { <span class="chip chip-red">@string.Format(T["audit.scan.sitesFailed"], _sitesFailed)</span> }
</div>
}
@if (_viewMode == "site")
{
<div class="text-muted mt-8" style="margin-bottom:8px">@T["audit.bysite.hint"]</div>
@foreach (var g in _results.GroupBy(r => (r.SiteUrl, r.SiteTitle)).OrderBy(g => g.Key.SiteTitle, StringComparer.OrdinalIgnoreCase))
{
var siteUrl = g.Key.SiteUrl;
var expanded = _expandedSites.Contains(siteUrl);
var hasHigh = g.Any(e => e.IsHighPrivilege);
<div class="site-drill @(expanded ? "open" : "")">
<button class="site-drill-header" @onclick="() => ToggleSite(siteUrl)">
<span class="drill-caret @(expanded ? "open" : "")">▸</span>
<span class="drill-title">@g.Key.SiteTitle</span>
<span class="text-muted drill-url">@g.Key.SiteUrl</span>
<span class="spacer"></span>
@if (hasHigh) { <span class="chip chip-red">@T["audit.chip.high"]</span> }
<span class="count-badge">@g.Count() @T["report.text.permissions_parens"]</span>
</button>
@if (expanded)
{
<div class="site-drill-body">
<div class="data-table-wrap">
<table class="data-table">
<thead><tr>
@if (_multiUser) { <th>@T["report.col.user"]</th> }
<th>@T["report.col.object"]</th>
<th>@T["audit.col.permission"]<HelpTip Text="@T["help.permissionLevel"]" /></th>
<th>@T["report.col.access_type"]<HelpTip Text="@T["help.accessType"]" Wide="true" /></th>
<th>@T["report.col.granted_through"]<HelpTip Text="@T["help.grantedThrough"]" /></th>
</tr></thead>
<tbody>
@foreach (var r in g)
{
<tr>
@if (_multiUser) { <td>@r.UserDisplayName</td> }
<td>@r.ObjectTitle <span class="text-muted">(@r.ObjectType)</span></td>
<td>@r.PermissionLevel @if (r.IsHighPrivilege) { <span class="chip chip-red">@T["audit.chip.high"]</span> }</td>
<td>@r.AccessType</td>
<td>@r.GrantedThrough</td>
</tr>
}
</tbody>
</table>
</div>
</div>
}
</div>
}
}
else
{
<div class="data-table-wrap">
<table class="data-table">
<thead><tr><th>@T["report.col.user"]</th><th>@T["report.col.site"]</th><th>@T["report.col.object"]</th><th>@T["audit.col.permission"]<HelpTip Text="@T["help.permissionLevel"]" /></th><th>@T["report.col.access_type"]<HelpTip Text="@T["help.accessType"]" Wide="true" /></th><th>@T["report.col.granted_through"]<HelpTip Text="@T["help.grantedThrough"]" /></th></tr></thead>
<tbody>
@foreach (var r in _results.Take(500))
{
<tr>
<td>@r.UserDisplayName</td>
<td>@r.SiteTitle</td>
<td>@r.ObjectTitle <span class="text-muted">(@r.ObjectType)</span></td>
<td>@r.PermissionLevel @if (r.IsHighPrivilege) { <span class="chip chip-red">@T["audit.chip.high"]</span> }</td>
<td>@r.AccessType</td>
<td>@r.GrantedThrough</td>
</tr>
}
</tbody>
</table>
</div>
@if (_results.Count > 500) { <div class="text-muted mt-8">@T["audit.msg.showFirst500Export"]</div> }
}
</div>
}
@code {
private string _users = string.Empty;
private bool _includeGuests, _loadingUsers;
private int _loadCount;
private string _userFilter = string.Empty;
private List<GraphDirectoryUser> _directoryUsers = new();
private readonly HashSet<string> _selectedEmails = new(StringComparer.OrdinalIgnoreCase);
private List<SiteInfo> _sites = new();
private IEnumerable<GraphDirectoryUser> FilteredUsers => string.IsNullOrWhiteSpace(_userFilter)
? _directoryUsers
: _directoryUsers.Where(u => u.DisplayName.Contains(_userFilter, StringComparison.OrdinalIgnoreCase)
|| u.UserPrincipalName.Contains(_userFilter, StringComparison.OrdinalIgnoreCase)
|| (u.Mail?.Contains(_userFilter, StringComparison.OrdinalIgnoreCase) ?? false));
private async Task LoadUsers()
{
_error = string.Empty; _loadingUsers = true; _loadCount = 0;
var progress = new Progress<int>(c => { _loadCount = c; InvokeAsync(StateHasChanged); });
try
{
_directoryUsers = (await GraphSvc.GetUsersAsync(Session.CurrentProfile!, _includeGuests, progress)).ToList();
}
catch (Exception ex) { _error = ex.Message; }
finally { _loadingUsers = false; await InvokeAsync(StateHasChanged); }
}
private void ToggleUser(string email, bool selected)
{
if (selected) _selectedEmails.Add(email); else _selectedEmails.Remove(email);
}
private void SelectAllFiltered()
{
foreach (var u in FilteredUsers) _selectedEmails.Add(u.Mail ?? u.UserPrincipalName);
}
private void ClearSelection() => _selectedEmails.Clear();
private bool _includeInherited, _includeSubsites, _scanFolders = true;
private bool _running; private string _status = string.Empty, _error = string.Empty;
private int _current, _total;
private List<UserAccessEntry> _results = new();
private int _sitesScanned, _sitesDenied, _sitesFailed;
private CancellationTokenSource? _cts;
// Results presentation: "site" = drill-down grouped by site (pick user → sites → click → detail);
// "flat" = the original per-entry table. Site view is default and matches the single-user flow.
private string _viewMode = "site";
private readonly HashSet<string> _expandedSites = new(StringComparer.OrdinalIgnoreCase);
// Show the User column inside the per-site detail only when the audit spans multiple users.
private bool _multiUser => _results.Select(r => r.UserLogin).Distinct(StringComparer.OrdinalIgnoreCase).Count() > 1;
private void ToggleSite(string siteUrl)
{
if (!_expandedSites.Remove(siteUrl)) _expandedSites.Add(siteUrl);
}
private async Task RunAudit()
{
_error = string.Empty; _results.Clear(); _expandedSites.Clear();
_sitesScanned = _sitesDenied = _sitesFailed = 0; _running = true;
_cts = new CancellationTokenSource();
var userList = _selectedEmails
.Concat(_users.Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
.Distinct(StringComparer.OrdinalIgnoreCase).ToList();
if (!userList.Any()) { _error = T["audit.err.noUsersOrEmail"]; _running = false; return; }
var siteList = _sites.ToList();
// No explicit selection → audit every site in the tenant. The scan itself is resilient
// (per-site errors are skipped) so a tenant-wide run completes despite denied/failed sites.
if (siteList.Count == 0)
{
_status = T["audit.status.discoveringSites"];
await InvokeAsync(StateHasChanged);
try
{
siteList = (await SiteDiscovery.SearchSitesAsync(Session.CurrentProfile!, null, _cts.Token)).ToList();
}
catch (OperationCanceledException) { _status = T["audit.status.cancelled"]; _running = false; return; }
catch (Exception ex) { _error = string.Format(T["audit.err.discoverFailed"], ex.Message); _running = false; return; }
// Enumeration came back empty → fall back to the profile root site.
if (siteList.Count == 0)
siteList.Add(new SiteInfo(Session.CurrentProfile!.TenantUrl, Session.CurrentProfile.Name));
}
var progress = new Progress<OperationProgress>(p => { _status = p.Message; _current = p.Current; _total = p.Total; InvokeAsync(StateHasChanged); });
try
{
var opts = new ScanOptions(_includeInherited, _scanFolders, 1, _includeSubsites);
var res = await AuditSvc.AuditUsersAsync(SessionMgr, Session.CurrentProfile!, userList, siteList, opts, progress, _cts.Token);
_results = res.Entries.ToList();
_sitesScanned = res.SitesScanned; _sitesDenied = res.SitesDenied; _sitesFailed = res.SitesFailed;
_status = string.Format(T["audit.status.found"], _results.Count);
await Audit.LogAsync("UserAccessAudit", Session.CurrentProfile?.Name ?? "", siteList.Select(s => s.Url),
$"{_results.Count} entries for {userList.Count} user(s); {res.SitesScanned} sites, {res.SitesDenied} denied, {res.SitesFailed} failed");
}
catch (OperationCanceledException) { _status = T["audit.status.cancelled"]; }
catch (Exception ex) { _error = ex.Message; }
finally { _running = false; await InvokeAsync(StateHasChanged); }
}
private void Cancel() => _cts?.Cancel();
private async Task ExportCsv() { await WebExport.DownloadCsvAsync(CsvExport.BuildCsv(_results.FirstOrDefault()?.UserDisplayName ?? "Users", _results.FirstOrDefault()?.UserLogin ?? "", _results), $"user_audit_{DateTime.Now:yyyyMMdd_HHmmss}.csv"); }
private async Task ExportHtml() { await WebExport.DownloadHtmlAsync(HtmlExport.BuildHtml(_results, branding: Session.CurrentBranding), $"user_audit_{DateTime.Now:yyyyMMdd_HHmmss}.html"); }
}