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

91 lines
3.7 KiB
C#

using Microsoft.Graph.Models;
using Microsoft.Graph.Users.Item.SendMail;
using SharepointToolbox.Web.Core.Models;
using SharepointToolbox.Web.Infrastructure.Auth;
namespace SharepointToolbox.Web.Services.Reports;
/// <summary>
/// Delivers a generated report by email through Graph. Uses the client's app-only
/// (certificate) Graph client, which has no signed-in user, so it posts to
/// <c>/users/{From}/sendMail</c> — the configured sender mailbox must exist in the
/// tenant and the app registration must hold the <c>Mail.Send</c> application role.
/// </summary>
public class ReportMailService : IReportMailService
{
// Graph caps a single sendMail request at ~4 MB total; larger files need an upload
// session we don't implement. Reject early with a clear message instead of a 413.
private const long MaxAttachmentBytes = 3 * 1024 * 1024;
private readonly IAppOnlyContextFactory _appOnly;
public ReportMailService(IAppOnlyContextFactory appOnly) { _appOnly = appOnly; }
public async Task SendAsync(
TenantProfile profile,
ScheduledReport schedule,
ReportEmailSettings settings,
string fileName,
string mime,
byte[] bytes,
CancellationToken ct = default)
{
if (string.IsNullOrWhiteSpace(settings.From))
throw new InvalidOperationException("No sender mailbox (From) configured for report email.");
var to = CleanAddresses(settings.To);
var cc = CleanAddresses(settings.Cc);
if (to.Count == 0 && cc.Count == 0)
throw new InvalidOperationException("Report email has no To or Cc recipients.");
var message = new Message
{
Subject = Substitute(settings.Subject, profile, schedule, fileName),
Body = new ItemBody
{
ContentType = BodyType.Html,
Content = Substitute(settings.Body, profile, schedule, fileName)
},
ToRecipients = to.Select(Recipient).ToList(),
CcRecipients = cc.Select(Recipient).ToList(),
};
if (bytes.LongLength > MaxAttachmentBytes)
throw new InvalidOperationException(
$"Report '{fileName}' is {bytes.LongLength / 1024.0 / 1024.0:F1} MB — too large to email " +
$"(Graph sendMail limit ~{MaxAttachmentBytes / 1024 / 1024} MB).");
message.Attachments = new List<Attachment>
{
new FileAttachment
{
OdataType = "#microsoft.graph.fileAttachment",
Name = fileName,
ContentType = mime,
ContentBytes = bytes,
}
};
var graph = await _appOnly.CreateGraphClientAsync(profile, ct);
await graph.Users[settings.From].SendMail.PostAsync(
new SendMailPostRequestBody { Message = message, SaveToSentItems = false }, cancellationToken: ct);
}
private static List<string> CleanAddresses(IEnumerable<string> raw) =>
raw.Select(a => a?.Trim() ?? string.Empty)
.Where(a => a.Length > 0)
.Distinct(StringComparer.OrdinalIgnoreCase)
.ToList();
private static Recipient Recipient(string address) =>
new() { EmailAddress = new EmailAddress { Address = address } };
private static string Substitute(string template, TenantProfile profile, ScheduledReport schedule, string fileName) =>
(template ?? string.Empty)
.Replace("{ReportName}", schedule.Name)
.Replace("{ClientName}", profile.Name)
.Replace("{ReportType}", schedule.Type.ToString())
.Replace("{FileName}", fileName)
.Replace("{DateUtc}", DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm"));
}