using OpenWaf.Domain.Policy;
namespace OpenWaf.Edge.Configuration;
///
/// The configuration-shaped mirror of . It exists
/// because appsettings.json is strings: is a
/// record struct the configuration binder cannot build from "400-499", and a
/// TimeSpan written as "00:05:00" in a deployment file is friendlier than a
/// number of minutes. One explicit mapping, rather than a binder that quietly
/// leaves a default in place when the shape is wrong.
///
internal sealed class EdgePolicyOptions
{
public string Mode { get; set; } = "Observe";
public int StreakThreshold { get; set; } = 10;
public string StreakWindow { get; set; } = "00:05:00";
public string BanDuration { get; set; } = "01:00:00";
public string RefusalRange { get; set; } = "400-499";
public string ServerErrorRange { get; set; } = "500-599";
public string Geo { get; set; } = "Off";
public bool TrustProxyHeaders { get; set; }
public int MaxTrackedSources { get; set; } = 10_000;
public int Ipv4KeyPrefixLength { get; set; } = 32;
public int Ipv6KeyPrefixLength { get; set; } = 64;
public int EngineBlockStatus { get; set; } = 403;
public int OperatorBlockStatus { get; set; } = 301;
// Empty by default: the configuration binder appends to an existing
// collection rather than replacing it, so a non-empty default here would
// leave a duplicate target in every deployment.
public string[] DefaultRedirectTargets { get; set; } = [];
public EdgePolicy ToPolicy() => new()
{
Mode = Enum.TryParse(Mode, true, out var m) ? m : EnforcementMode.Observe,
StreakThreshold = StreakThreshold > 0 ? StreakThreshold : 10,
StreakWindow = ParseWindow(StreakWindow, TimeSpan.FromMinutes(5)),
BanDuration = ParseWindow(BanDuration, TimeSpan.FromHours(1)),
RefusalRange = StatusRange.Parse(RefusalRange, new StatusRange(400, 499)),
ServerErrorRange = StatusRange.Parse(ServerErrorRange, new StatusRange(500, 599)),
Geo = Enum.TryParse(Geo, true, out var g) ? g : GeoMode.Off,
TrustProxyHeaders = TrustProxyHeaders,
MaxTrackedSources = MaxTrackedSources > 0 ? MaxTrackedSources : 10_000,
Ipv4KeyPrefixLength = Ipv4KeyPrefixLength,
Ipv6KeyPrefixLength = Ipv6KeyPrefixLength,
EngineBlockStatus = EngineBlockStatus,
OperatorBlockStatus = OperatorBlockStatus,
DefaultRedirectTargets = DefaultRedirectTargets.Length == 0
? new[] { "https://www.iana.org/help/example-domains" }
: DefaultRedirectTargets
};
/// Accepts both 00:05:00 and a bare number of minutes.
private static TimeSpan ParseWindow(string value, TimeSpan fallback)
{
if (string.IsNullOrWhiteSpace(value)) return fallback;
if (TimeSpan.TryParse(value, out var ts)) return ts;
return double.TryParse(value, out var minutes) && minutes > 0 ? TimeSpan.FromMinutes(minutes) : fallback;
}
}