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

79 lines
3.3 KiB
C#

using System.Collections.Concurrent;
namespace SharepointToolbox.Web.Services.Reports;
/// <summary>
/// Process-wide coordinator for scheduled-report execution. Covers two operator needs:
/// • <b>Cancel an in-flight run</b> — every active run registers a linked
/// <see cref="CancellationTokenSource"/> keyed by schedule id, so the UI (or a
/// global stop) can abort a report that is currently executing, whether it was
/// started by the scheduler or by "Run now".
/// • <b>Pause future runs</b> — a global flag the background scheduler honours,
/// letting an admin suspend all cadence-triggered runs at once without toggling
/// each schedule's <c>Enabled</c> flag.
///
/// In-memory and singleton. The pause flag does NOT survive a process restart (a
/// restart resumes the scheduler); per-schedule <c>Enabled</c> flags persist and are
/// the durable way to keep a schedule off.
/// </summary>
public sealed class ScheduledRunCoordinator
{
private readonly ConcurrentDictionary<string, CancellationTokenSource> _active = new();
private volatile bool _paused;
/// <summary>True while the scheduler is globally paused (no schedules fire).</summary>
public bool IsPaused => _paused;
public void Pause() => _paused = true;
public void Resume() => _paused = false;
/// <summary>True while a run is registered for this schedule id.</summary>
public bool IsRunning(string scheduleId) => _active.ContainsKey(scheduleId);
/// <summary>Snapshot of schedule ids with a run in progress.</summary>
public IReadOnlyCollection<string> RunningIds => _active.Keys.ToArray();
/// <summary>
/// Registers a run for <paramref name="scheduleId"/> and returns a token that trips
/// when either the caller's <paramref name="linked"/> token (e.g. app shutdown) or a
/// <see cref="Cancel"/>/<see cref="CancelAll"/> call fires. Returns <c>null</c> if a
/// run is already registered for this schedule — callers must skip to avoid overlap.
/// Always pair a non-null return with <see cref="Complete"/> in a <c>finally</c>.
/// </summary>
public CancellationToken? TryBegin(string scheduleId, CancellationToken linked)
{
var cts = CancellationTokenSource.CreateLinkedTokenSource(linked);
if (!_active.TryAdd(scheduleId, cts)) { cts.Dispose(); return null; }
return cts.Token;
}
/// <summary>Deregisters and disposes the run for this schedule id.</summary>
public void Complete(string scheduleId)
{
if (_active.TryRemove(scheduleId, out var cts)) cts.Dispose();
}
/// <summary>Signals cancellation to the run for this schedule id. Returns false if none.</summary>
public bool Cancel(string scheduleId)
{
if (_active.TryGetValue(scheduleId, out var cts))
{
try { cts.Cancel(); return true; }
catch (ObjectDisposedException) { return false; } // completed between lookup and cancel
}
return false;
}
/// <summary>Signals cancellation to every run in progress. Returns the count signalled.</summary>
public int CancelAll()
{
int n = 0;
foreach (var cts in _active.Values)
{
try { cts.Cancel(); n++; }
catch (ObjectDisposedException) { /* completed concurrently */ }
}
return n;
}
}