Files
SharepointToolbox-Web/Infrastructure/Persistence/GeneratedReportRepository.cs
T
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

88 lines
3.2 KiB
C#

using System.Text;
using System.Text.Json;
using SharepointToolbox.Web.Core.Models;
namespace SharepointToolbox.Web.Infrastructure.Persistence;
/// <summary>
/// JSON-file index of produced report files (reports-index.json). The files
/// themselves live under {ExportsFolder}/{ProfileId}/; this is the catalogue the
/// per-client "Reports" list and the id-based download endpoint read.
/// </summary>
public class GeneratedReportRepository
{
private readonly string _filePath;
private readonly SemaphoreSlim _writeLock = new(1, 1);
private static readonly JsonSerializerOptions ReadOpts = new() { PropertyNameCaseInsensitive = true };
private static readonly JsonSerializerOptions WriteOpts = new()
{
WriteIndented = true,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
};
public GeneratedReportRepository(string filePath) { _filePath = filePath; }
public async Task<IReadOnlyList<GeneratedReport>> LoadAsync()
{
if (!File.Exists(_filePath)) return Array.Empty<GeneratedReport>();
string json;
try { json = await File.ReadAllTextAsync(_filePath, Encoding.UTF8); }
catch (IOException ex) { throw new InvalidDataException($"Failed to read report index: {_filePath}", ex); }
Root? root;
try { root = JsonSerializer.Deserialize<Root>(json, ReadOpts); }
catch (JsonException ex) { throw new InvalidDataException($"Invalid JSON in report index: {_filePath}", ex); }
return (IReadOnlyList<GeneratedReport>?)root?.Reports ?? Array.Empty<GeneratedReport>();
}
public async Task<GeneratedReport?> GetAsync(string id)
=> (await LoadAsync()).FirstOrDefault(r => r.Id == id);
public async Task<IReadOnlyList<GeneratedReport>> LoadForProfileAsync(string profileId)
{
var all = await LoadAsync();
return all.Where(r => r.ProfileId == profileId)
.OrderByDescending(r => r.GeneratedUtc)
.ToList();
}
public async Task AddAsync(GeneratedReport report)
{
await _writeLock.WaitAsync();
try
{
var list = (await LoadAsync()).ToList();
list.Add(report);
await WriteUnlockedAsync(list);
}
finally { _writeLock.Release(); }
}
public async Task DeleteAsync(string id)
{
await _writeLock.WaitAsync();
try
{
var list = (await LoadAsync()).ToList();
list.RemoveAll(r => r.Id == id);
await WriteUnlockedAsync(list);
}
finally { _writeLock.Release(); }
}
private async Task WriteUnlockedAsync(IReadOnlyList<GeneratedReport> reports)
{
var json = JsonSerializer.Serialize(new Root { Reports = reports.ToList() }, WriteOpts);
var tmpPath = _filePath + ".tmp";
var dir = Path.GetDirectoryName(_filePath);
if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir);
await File.WriteAllTextAsync(tmpPath, json, Encoding.UTF8);
JsonDocument.Parse(await File.ReadAllTextAsync(tmpPath, Encoding.UTF8)).Dispose();
File.Move(tmpPath, _filePath, overwrite: true);
}
private sealed class Root { public List<GeneratedReport> Reports { get; set; } = new(); }
}