Files
Febe/tools/Febe.Sonda/SanitizerAllowlist.cs
T

122 lines
4.7 KiB
C#

using System.Globalization;
using System.Text.Json;
using System.Text.RegularExpressions;
namespace Febe.Sonda;
/// <summary>Kind of a field that says nothing about a person (spec §14.5).</summary>
public enum AllowedField
{
None,
Dimension,
Duration,
Count,
Code,
Date,
}
/// <summary>
/// The short list of fields the sanitizer keeps (<c>ripulitura.json</c>): dimensions, durations, counts, type codes and
/// dates. Everything else is replaced. Booleans and null are always kept: they cannot identify anyone.
/// </summary>
public sealed partial class SanitizerAllowlist
{
private readonly List<(Regex Pattern, AllowedField Field)> _rules;
public SanitizerAllowlist(IEnumerable<(string KeyPattern, AllowedField Field)> rules)
{
_rules = [.. rules.Select(r => (new Regex("^" + Regex.Escape(r.KeyPattern.Trim().ToLowerInvariant()).Replace("\\*", ".*", StringComparison.Ordinal) + "$", RegexOptions.CultureInvariant), r.Field))];
}
/// <summary>The shipped list (embedded <c>ripulitura.json</c>).</summary>
public static SanitizerAllowlist Default { get; } = Parse(ReadEmbedded());
public static SanitizerAllowlist Load(string path) => Parse(File.ReadAllText(path));
public static SanitizerAllowlist Parse(string json)
{
using var document = JsonDocument.Parse(json, new JsonDocumentOptions { CommentHandling = JsonCommentHandling.Skip, AllowTrailingCommas = true });
var rules = new List<(string, AllowedField)>();
if (!document.RootElement.TryGetProperty("categories", out var categories) || categories.ValueKind != JsonValueKind.Object)
{
throw new InvalidDataException("ripulitura.json: manca «categories».");
}
foreach (var category in categories.EnumerateObject())
{
var field = category.Name.ToLowerInvariant() switch
{
"dimension" => AllowedField.Dimension,
"duration" => AllowedField.Duration,
"count" => AllowedField.Count,
"code" => AllowedField.Code,
"date" => AllowedField.Date,
_ => throw new InvalidDataException($"ripulitura.json: categoria «{category.Name}» sconosciuta (ammesse: dimension, duration, count, code, date)."),
};
if (category.Value.TryGetProperty("keys", out var keys) && keys.ValueKind == JsonValueKind.Array)
{
foreach (var key in keys.EnumerateArray())
{
if (key.GetString() is { Length: > 0 } pattern)
{
rules.Add((pattern, field));
}
}
}
}
return new SanitizerAllowlist(rules);
}
public AllowedField FieldOf(string? key)
{
if (string.IsNullOrEmpty(key))
{
return AllowedField.None;
}
var lower = key.ToLowerInvariant();
foreach (var (pattern, field) in _rules)
{
if (pattern.IsMatch(lower))
{
return field;
}
}
return AllowedField.None;
}
/// <summary>True when a number under <paramref name="key"/> is kept as it is.</summary>
public bool KeepsNumber(string? key) => FieldOf(key) != AllowedField.None;
/// <summary>True when a string under <paramref name="key"/> is kept: short type codes, and dates under date keys.</summary>
public bool KeepsString(string? key, string value) => FieldOf(key) switch
{
AllowedField.Code => value.Length <= 40 && CodeShape().IsMatch(value) && !LongDigits().IsMatch(value),
AllowedField.Date => value.Length <= 40 && (DateShape().IsMatch(value)
|| (UnixShape().IsMatch(value) && long.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out _))),
_ => false,
};
private static string ReadEmbedded()
{
using var stream = typeof(SanitizerAllowlist).Assembly.GetManifestResourceStream("Febe.Sonda.ripulitura.json")
?? throw new FileNotFoundException("Risorsa incorporata mancante: ripulitura.json");
using var reader = new StreamReader(stream);
return reader.ReadToEnd();
}
[GeneratedRegex(@"^[A-Za-z][A-Za-z0-9_./+\- ]*$", RegexOptions.CultureInvariant)]
private static partial Regex CodeShape();
[GeneratedRegex(@"\d{3,}", RegexOptions.CultureInvariant)]
private static partial Regex LongDigits();
[GeneratedRegex(@"^\d{4}-\d{2}-\d{2}([T ]\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:?\d{2})?)?$", RegexOptions.CultureInvariant)]
private static partial Regex DateShape();
[GeneratedRegex(@"^\d{9,13}$", RegexOptions.CultureInvariant)]
private static partial Regex UnixShape();
}