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>
This commit is contained in:
@@ -0,0 +1,70 @@
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
using Microsoft.AspNetCore.DataProtection;
|
||||
|
||||
namespace SharepointToolbox.Web.Infrastructure.Auth;
|
||||
|
||||
/// <summary>
|
||||
/// File-backed <see cref="IAppOnlyCertStore"/>. Each profile's certificate is
|
||||
/// re-exported password-less, encrypted with ASP.NET Core Data Protection, and
|
||||
/// written to {certsFolder}/{profileId}.bin. The uploaded PFX password is consumed
|
||||
/// at save time and never persisted.
|
||||
/// </summary>
|
||||
public class AppOnlyCertStore : IAppOnlyCertStore
|
||||
{
|
||||
private const string Purpose = "SharepointToolbox.AppOnlyCert.v1";
|
||||
|
||||
private readonly string _certsFolder;
|
||||
private readonly IDataProtector _protector;
|
||||
|
||||
public AppOnlyCertStore(string certsFolder, IDataProtectionProvider dataProtection)
|
||||
{
|
||||
_certsFolder = certsFolder;
|
||||
_protector = dataProtection.CreateProtector(Purpose);
|
||||
Directory.CreateDirectory(_certsFolder);
|
||||
}
|
||||
|
||||
private string PathFor(string profileId) => Path.Combine(_certsFolder, $"{profileId}.bin");
|
||||
|
||||
public async Task<string> SaveAsync(string profileId, byte[] pfxBytes, string? password, CancellationToken ct = default)
|
||||
{
|
||||
// Open the uploaded PFX (Exportable so we can re-emit a password-less copy that
|
||||
// the loader can open later without prompting). EphemeralKeySet keeps the key
|
||||
// out of the Windows certificate store during this transient operation.
|
||||
using var cert = X509CertificateLoader.LoadPkcs12(
|
||||
pfxBytes, password,
|
||||
X509KeyStorageFlags.Exportable | X509KeyStorageFlags.EphemeralKeySet);
|
||||
|
||||
if (!cert.HasPrivateKey)
|
||||
throw new InvalidOperationException("The uploaded certificate has no private key. Export the PFX with its key.");
|
||||
|
||||
var passwordless = cert.Export(X509ContentType.Pkcs12);
|
||||
var protectedBytes = _protector.Protect(passwordless);
|
||||
|
||||
Directory.CreateDirectory(_certsFolder);
|
||||
var tmp = PathFor(profileId) + ".tmp";
|
||||
await File.WriteAllBytesAsync(tmp, protectedBytes, ct);
|
||||
File.Move(tmp, PathFor(profileId), overwrite: true);
|
||||
|
||||
return cert.Thumbprint;
|
||||
}
|
||||
|
||||
public async Task<X509Certificate2?> LoadAsync(string profileId, CancellationToken ct = default)
|
||||
{
|
||||
var path = PathFor(profileId);
|
||||
if (!File.Exists(path)) return null;
|
||||
|
||||
var protectedBytes = await File.ReadAllBytesAsync(path, ct);
|
||||
var pfx = _protector.Unprotect(protectedBytes);
|
||||
return X509CertificateLoader.LoadPkcs12(
|
||||
pfx, password: null,
|
||||
X509KeyStorageFlags.Exportable | X509KeyStorageFlags.EphemeralKeySet);
|
||||
}
|
||||
|
||||
public bool Exists(string profileId) => File.Exists(PathFor(profileId));
|
||||
|
||||
public void Delete(string profileId)
|
||||
{
|
||||
var path = PathFor(profileId);
|
||||
if (File.Exists(path)) File.Delete(path);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
using Azure.Core;
|
||||
using Azure.Identity;
|
||||
using Microsoft.Graph;
|
||||
using Microsoft.SharePoint.Client;
|
||||
using SharepointToolbox.Web.Core.Models;
|
||||
|
||||
namespace SharepointToolbox.Web.Infrastructure.Auth;
|
||||
|
||||
/// <summary>
|
||||
/// Certificate-based app-only client factory. Acquires tokens with
|
||||
/// <see cref="ClientCertificateCredential"/> and injects the SharePoint bearer token
|
||||
/// through CSOM's <c>ExecutingWebRequest</c> hook — the same mechanism the delegated
|
||||
/// <c>SessionManager</c> uses, so report services see an ordinary authenticated
|
||||
/// <see cref="ClientContext"/> regardless of which auth model produced it.
|
||||
/// </summary>
|
||||
public class AppOnlyContextFactory : IAppOnlyContextFactory
|
||||
{
|
||||
private static readonly string[] GraphScopes = ["https://graph.microsoft.com/.default"];
|
||||
|
||||
private readonly IAppOnlyCertStore _certStore;
|
||||
|
||||
public AppOnlyContextFactory(IAppOnlyCertStore certStore) { _certStore = certStore; }
|
||||
|
||||
public bool IsConfigured(TenantProfile profile) =>
|
||||
profile.AppOnlyEnabled
|
||||
&& !string.IsNullOrWhiteSpace(profile.AppOnlyClientId)
|
||||
&& !string.IsNullOrWhiteSpace(profile.TenantId)
|
||||
&& _certStore.Exists(profile.Id);
|
||||
|
||||
public async Task<AccessToken> GetTokenAsync(TenantProfile profile, string scope, CancellationToken ct = default)
|
||||
{
|
||||
var credential = await BuildCredentialAsync(profile, ct);
|
||||
return await credential.GetTokenAsync(new TokenRequestContext([scope]), ct);
|
||||
}
|
||||
|
||||
public async Task<ClientContext> CreateContextAsync(TenantProfile profile, string siteUrl, CancellationToken ct = default)
|
||||
{
|
||||
var credential = await BuildCredentialAsync(profile, ct);
|
||||
var spScope = SharePointScope(siteUrl);
|
||||
|
||||
var ctx = new ClientContext(siteUrl);
|
||||
ctx.ExecutingWebRequest += (_, e) =>
|
||||
{
|
||||
// CSOM raises this synchronously immediately before sending; acquire the
|
||||
// token synchronously so the header is guaranteed set. ClientCertificateCredential
|
||||
// caches access tokens internally, so this is cheap after the first call.
|
||||
var token = credential.GetToken(new TokenRequestContext([spScope]), CancellationToken.None);
|
||||
e.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + token.Token;
|
||||
};
|
||||
return ctx;
|
||||
}
|
||||
|
||||
public async Task<GraphServiceClient> CreateGraphClientAsync(TenantProfile profile, CancellationToken ct = default)
|
||||
{
|
||||
var credential = await BuildCredentialAsync(profile, ct);
|
||||
return new GraphServiceClient(credential, GraphScopes);
|
||||
}
|
||||
|
||||
public async Task<string?> TestConnectionAsync(TenantProfile profile, CancellationToken ct = default)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var ctx = await CreateContextAsync(profile, profile.TenantUrl, ct);
|
||||
ctx.Load(ctx.Web, w => w.Title);
|
||||
await ctx.ExecuteQueryAsync();
|
||||
return null;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return ex.Message;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<string?> WaitUntilReadyAsync(TenantProfile profile, TimeSpan timeout, CancellationToken ct = default)
|
||||
{
|
||||
var deadline = DateTimeOffset.UtcNow + timeout;
|
||||
var delay = TimeSpan.FromSeconds(5);
|
||||
string? lastError;
|
||||
do
|
||||
{
|
||||
// Each attempt builds a fresh credential, so a cached 401 never sticks across retries.
|
||||
lastError = await TestConnectionAsync(profile, ct);
|
||||
if (lastError is null) return null;
|
||||
if (DateTimeOffset.UtcNow + delay >= deadline) break;
|
||||
await Task.Delay(delay, ct);
|
||||
}
|
||||
while (DateTimeOffset.UtcNow < deadline);
|
||||
|
||||
return lastError;
|
||||
}
|
||||
|
||||
private async Task<ClientCertificateCredential> BuildCredentialAsync(TenantProfile profile, CancellationToken ct)
|
||||
{
|
||||
if (!profile.AppOnlyEnabled)
|
||||
throw new InvalidOperationException($"App-only reports are not enabled for client '{profile.Name}'.");
|
||||
if (string.IsNullOrWhiteSpace(profile.AppOnlyClientId))
|
||||
throw new InvalidOperationException($"No app-only client ID configured for client '{profile.Name}'.");
|
||||
if (string.IsNullOrWhiteSpace(profile.TenantId))
|
||||
throw new InvalidOperationException($"No tenant ID configured for client '{profile.Name}'.");
|
||||
|
||||
var cert = await _certStore.LoadAsync(profile.Id, ct)
|
||||
?? throw new InvalidOperationException($"No app-only certificate stored for client '{profile.Name}'.");
|
||||
|
||||
var options = new ClientCertificateCredentialOptions
|
||||
{
|
||||
// SharePoint app-only requires the v1 resource audience; SendCertificateChain
|
||||
// improves compatibility with subject-name/issuer-configured app registrations.
|
||||
SendCertificateChain = true
|
||||
};
|
||||
return new ClientCertificateCredential(profile.TenantId, profile.AppOnlyClientId, cert, options);
|
||||
}
|
||||
|
||||
// https://contoso.sharepoint.com/sites/Foo → https://contoso.sharepoint.com/.default
|
||||
private static string SharePointScope(string siteUrl)
|
||||
{
|
||||
if (Uri.TryCreate(siteUrl, UriKind.Absolute, out var uri))
|
||||
return $"{uri.Scheme}://{uri.Host}/.default";
|
||||
return siteUrl.TrimEnd('/') + "/.default";
|
||||
}
|
||||
}
|
||||
@@ -5,22 +5,34 @@ using SharepointToolbox.Web.Services.Session;
|
||||
|
||||
namespace SharepointToolbox.Web.Infrastructure.Auth;
|
||||
|
||||
/// <summary>Delegated Graph client using OAuth2 refresh-token flow via ISessionManager.</summary>
|
||||
/// <summary>
|
||||
/// Builds a Graph client for a profile. Certificate-configured profiles get an app-only
|
||||
/// client (no interactive sign-in); all others use the delegated OAuth2 refresh-token flow
|
||||
/// via ISessionManager.
|
||||
/// </summary>
|
||||
public class GraphClientFactory
|
||||
{
|
||||
private readonly ISessionCredentialStore _credentialStore;
|
||||
private readonly ISessionManager _sessionManager;
|
||||
private readonly IAppOnlyContextFactory _appOnly;
|
||||
|
||||
public GraphClientFactory(ISessionCredentialStore credentialStore, ISessionManager sessionManager)
|
||||
public GraphClientFactory(
|
||||
ISessionCredentialStore credentialStore,
|
||||
ISessionManager sessionManager,
|
||||
IAppOnlyContextFactory appOnly)
|
||||
{
|
||||
_credentialStore = credentialStore;
|
||||
_sessionManager = sessionManager;
|
||||
_appOnly = appOnly;
|
||||
}
|
||||
|
||||
public async Task<GraphServiceClient> CreateClientAsync(TenantProfile profile)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrEmpty(profile.TenantId);
|
||||
|
||||
if (_appOnly.IsConfigured(profile))
|
||||
return await _appOnly.CreateGraphClientAsync(profile);
|
||||
|
||||
var hasTokens = await _credentialStore.HasCredentialsAsync();
|
||||
if (!hasTokens)
|
||||
throw new InvalidOperationException(
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
|
||||
namespace SharepointToolbox.Web.Infrastructure.Auth;
|
||||
|
||||
/// <summary>
|
||||
/// Stores the per-client app-only certificate (private key included) encrypted at
|
||||
/// rest, keyed by profile id. Used only by the background scheduler — never exposed
|
||||
/// to the browser.
|
||||
/// </summary>
|
||||
public interface IAppOnlyCertStore
|
||||
{
|
||||
/// <summary>
|
||||
/// Persists an uploaded PFX for a profile. Returns the certificate thumbprint.
|
||||
/// The uploaded password is used only to open the PFX; it is not retained.
|
||||
/// </summary>
|
||||
Task<string> SaveAsync(string profileId, byte[] pfxBytes, string? password, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Loads the stored certificate (with private key) for app-only auth, or null if none.</summary>
|
||||
Task<X509Certificate2?> LoadAsync(string profileId, CancellationToken ct = default);
|
||||
|
||||
bool Exists(string profileId);
|
||||
|
||||
void Delete(string profileId);
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
using Azure.Core;
|
||||
using Microsoft.Graph;
|
||||
using Microsoft.SharePoint.Client;
|
||||
using SharepointToolbox.Web.Core.Models;
|
||||
|
||||
namespace SharepointToolbox.Web.Infrastructure.Auth;
|
||||
|
||||
/// <summary>
|
||||
/// Builds app-only (certificate-based) clients for a client profile. Drives BOTH the
|
||||
/// background report scheduler AND the interactive session: when a profile is configured
|
||||
/// for certificate auth (see <see cref="IsConfigured"/>), technicians operate through the
|
||||
/// app identity and never sign in to SharePoint per profile. Requires
|
||||
/// <see cref="TenantProfile.AppOnlyEnabled"/>, an app-only client id, and a stored certificate.
|
||||
/// </summary>
|
||||
public interface IAppOnlyContextFactory
|
||||
{
|
||||
/// <summary>
|
||||
/// True when this profile can authenticate app-only without an interactive sign-in:
|
||||
/// <see cref="TenantProfile.AppOnlyEnabled"/> is set, an app-only client id is present,
|
||||
/// and a certificate is stored for the profile. When false, callers fall back to the
|
||||
/// delegated refresh-token flow.
|
||||
/// </summary>
|
||||
bool IsConfigured(TenantProfile profile);
|
||||
|
||||
/// <summary>CSOM context for a specific site, authenticated app-only.</summary>
|
||||
Task<ClientContext> CreateContextAsync(TenantProfile profile, string siteUrl, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Microsoft Graph client, authenticated app-only.</summary>
|
||||
Task<GraphServiceClient> CreateGraphClientAsync(TenantProfile profile, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Acquires an app-only access token for an arbitrary scope (e.g. a SharePoint host or Graph).</summary>
|
||||
Task<AccessToken> GetTokenAsync(TenantProfile profile, string scope, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Verifies the stored credentials can authenticate against the tenant root web.
|
||||
/// Returns null on success, or an error message describing the failure.
|
||||
/// </summary>
|
||||
Task<string?> TestConnectionAsync(TenantProfile profile, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Polls <see cref="TestConnectionAsync"/> until it succeeds or <paramref name="timeout"/>
|
||||
/// elapses. After a fresh app registration, the certificate key credential and app-role
|
||||
/// admin consent take time to propagate through Entra (token requests 401 until then);
|
||||
/// this waits that window out. Returns null once ready, or the last error on timeout.
|
||||
/// </summary>
|
||||
Task<string?> WaitUntilReadyAsync(TenantProfile profile, TimeSpan timeout, CancellationToken ct = default);
|
||||
}
|
||||
@@ -7,23 +7,31 @@ using SharepointToolbox.Web.Services.Session;
|
||||
namespace SharepointToolbox.Web.Infrastructure.Auth;
|
||||
|
||||
/// <summary>
|
||||
/// Delegated session manager using OAuth2 refresh tokens.
|
||||
/// Tokens come from ISessionCredentialStore (ProtectedSessionStorage — browser-side only).
|
||||
/// Caches access tokens in-memory per scope for the duration of the Blazor circuit.
|
||||
/// Session manager that resolves the auth model per profile. When a profile is configured
|
||||
/// for certificate auth (<see cref="IAppOnlyContextFactory.IsConfigured"/>), contexts are
|
||||
/// built app-only via the stored certificate and no interactive sign-in is required.
|
||||
/// Otherwise it falls back to the delegated OAuth2 refresh-token flow, whose access tokens
|
||||
/// come from ISessionCredentialStore (ProtectedSessionStorage — browser-side only) and are
|
||||
/// cached in-memory per scope for the duration of the Blazor circuit.
|
||||
/// Scoped per Blazor circuit.
|
||||
/// </summary>
|
||||
public class SessionManager : ISessionManager
|
||||
{
|
||||
private readonly ISessionCredentialStore _credentialStore;
|
||||
private readonly ITokenRefreshService _tokenRefresh;
|
||||
private readonly IAppOnlyContextFactory _appOnly;
|
||||
private readonly Dictionary<string, ClientContext> _contexts = new();
|
||||
private readonly Dictionary<string, (string Token, DateTimeOffset ExpiresAt)> _accessTokenCache = new();
|
||||
private readonly SemaphoreSlim _lock = new(1, 1);
|
||||
|
||||
public SessionManager(ISessionCredentialStore credentialStore, ITokenRefreshService tokenRefresh)
|
||||
public SessionManager(
|
||||
ISessionCredentialStore credentialStore,
|
||||
ITokenRefreshService tokenRefresh,
|
||||
IAppOnlyContextFactory appOnly)
|
||||
{
|
||||
_credentialStore = credentialStore;
|
||||
_tokenRefresh = tokenRefresh;
|
||||
_appOnly = appOnly;
|
||||
}
|
||||
|
||||
public bool IsAuthenticated(string tenantUrl) => _contexts.ContainsKey(NormalizeUrl(tenantUrl));
|
||||
@@ -62,6 +70,24 @@ public class SessionManager : ISessionManager
|
||||
var key = NormalizeUrl(profile.TenantUrl);
|
||||
var spScope = NormalizeScopeUrl(profile.TenantUrl) + "/.default";
|
||||
|
||||
// Certificate-configured profiles authenticate app-only: no interactive sign-in,
|
||||
// no session tokens. Build the context through the cert factory and cache it under
|
||||
// the same key so report services see an ordinary authenticated ClientContext.
|
||||
if (_appOnly.IsConfigured(profile))
|
||||
{
|
||||
await _lock.WaitAsync(ct);
|
||||
try
|
||||
{
|
||||
if (_contexts.TryGetValue(key, out var existingCert))
|
||||
return existingCert;
|
||||
|
||||
var certCtx = await _appOnly.CreateContextAsync(profile, profile.TenantUrl, ct);
|
||||
_contexts[key] = certCtx;
|
||||
return certCtx;
|
||||
}
|
||||
finally { _lock.Release(); }
|
||||
}
|
||||
|
||||
await _lock.WaitAsync(ct);
|
||||
try
|
||||
{
|
||||
@@ -90,16 +116,7 @@ public class SessionManager : ISessionManager
|
||||
|
||||
public async Task<ClientContext> GetOrCreateContextAsync(string siteUrl, TenantProfile profile, CancellationToken ct = default)
|
||||
{
|
||||
var profileForSite = new TenantProfile
|
||||
{
|
||||
Id = profile.Id,
|
||||
Name = profile.Name,
|
||||
TenantUrl = siteUrl,
|
||||
TenantId = profile.TenantId,
|
||||
ClientId = profile.ClientId,
|
||||
ClientLogo = profile.ClientLogo,
|
||||
};
|
||||
return await GetOrCreateContextAsync(profileForSite, ct);
|
||||
return await GetOrCreateContextAsync(profile.CloneForSite(siteUrl), ct);
|
||||
}
|
||||
|
||||
public async Task ClearSessionAsync(string tenantUrl)
|
||||
|
||||
Reference in New Issue
Block a user