From edadfe1194c2e0c68f863e61af35ee2a58f67d42 Mon Sep 17 00:00:00 2001 From: Chrison Simtian Date: Sun, 25 Oct 2026 21:06:47 +1300 Subject: [PATCH 1/2] Add custom NAT rules to the legacy client --- README.md | 21 ++ src/UnifiSharp/Legacy/UnifiLegacyClient.cs | 86 ++++++ src/UnifiSharp/Legacy/UnifiNatRule.cs | 74 +++++ src/UnifiSharp/Legacy/UnifiNatRuleJson.cs | 117 ++++++++ .../UnifiSharp.Tests/UnifiLegacyLiveTests.cs | 12 + tests/UnifiSharp.Tests/UnifiNatRuleTests.cs | 283 ++++++++++++++++++ 6 files changed, 593 insertions(+) create mode 100644 src/UnifiSharp/Legacy/UnifiNatRule.cs create mode 100644 src/UnifiSharp/Legacy/UnifiNatRuleJson.cs create mode 100644 tests/UnifiSharp.Tests/UnifiNatRuleTests.cs diff --git a/README.md b/README.md index afd2116..34d09d4 100644 --- a/README.md +++ b/README.md @@ -186,6 +186,27 @@ var dns = NetworkDhcpDns.Read(net); // null = a await legacy.ReplaceNetworkRawAsync(id, NetworkDhcpDns.With(net, ["10.20.0.53", "10.20.0.54"])); ``` +**Custom NAT rules** (DNAT, MASQUERADE, SNAT) are on the v2 side too (`…/v2/api/site//nat`), +so the update is a full replacement. A rule has no name, so `UnifiNatRuleSpec.Name` is its +`description`, and callers reconcile by it. `in_interface` / `out_interface` are network +`_id`s; the spec takes network names and `GetNatNamesAsync` resolves them. The controller +rejects a duplicate `rule_index`, so `CreateNatRuleAsync` takes the next free one unless the spec +declares it. `UpdateNatRuleAsync` and `DeleteNatRuleAsync` refuse predefined rules and ids that +aren't on the controller. A filter matches one address, range or CIDR, with `InvertAddress` for +"everything except". The shape comes from the UCG (Network 10.6.106); a throwaway container has +no gateway and takes no NAT rule, so writes are unit-tested rather than container-tested. + +```csharp +var names = await legacy.GetNatNamesAsync(); +await legacy.CreateNatRuleAsync(new UnifiNatRuleSpec +{ + Name = "consumer-dns-redirect", Type = UnifiNatType.Dnat, Protocol = "tcp_udp", + InNetwork = "Consumer", TranslatedAddress = "10.20.0.53", TranslatedPort = "53", + Source = new() { Address = "10.20.0.53-10.20.0.54", InvertAddress = true }, + Destination = new() { Address = "10.20.0.53-10.20.0.54", Port = "53", InvertAddress = true }, +}, names); +``` + ## Firewall policies (`UnifiSharp.Firewall`) Zone-based firewall policies (UniFi Network 9+) go through the **official** integration API, diff --git a/src/UnifiSharp/Legacy/UnifiLegacyClient.cs b/src/UnifiSharp/Legacy/UnifiLegacyClient.cs index 3f7f977..31c1217 100644 --- a/src/UnifiSharp/Legacy/UnifiLegacyClient.cs +++ b/src/UnifiSharp/Legacy/UnifiLegacyClient.cs @@ -191,6 +191,92 @@ public async Task DeleteStaticDnsAsync(string id, CancellationToken ct = default await ReadV2Async(resp, "static-dns", ct).ConfigureAwait(false); // throws on failure } + // ── Custom NAT rules (v2 site API: nat) ─────────────────────────────────── + // Same surface as static-dns: bare JSON, full-replacement PUT. The controller rejects a + // duplicate rule_index (400 NatRuleInvalidParameters) and stores null for a missing one, + // so Create picks the next free index when the spec leaves it open (past every rule's, + // predefined included; two concurrent creates can still collide and the second gets the 400). + // Predefined rules are the gateway's own: Update and Delete refuse them. + + public async Task> ListNatRulesAsync(CancellationToken ct = default) + { + using var resp = await _session.SendAbsoluteAsync(HttpMethod.Get, NatUrl(), null, ct).ConfigureAwait(false); + var rows = await ReadV2Async>(resp, "nat", ct).ConfigureAwait(false) ?? []; + return rows.Select(ParseNat).ToList(); + } + + /// Network name → _id, the form in_interface / out_interface take. + public async Task GetNatNamesAsync(CancellationToken ct = default) + { + var nets = await ListNetworksAsync(ct).ConfigureAwait(false); + return new UnifiNatNames(nets.Where(n => n.Name is not null && n.Id is not null) + .GroupBy(n => n.Name!, StringComparer.OrdinalIgnoreCase) + .ToDictionary(g => g.Key, g => g.First().Id!, StringComparer.OrdinalIgnoreCase)); + } + + public async Task CreateNatRuleAsync(UnifiNatRuleSpec spec, UnifiNatNames names, CancellationToken ct = default) + { + var body = UnifiNatRuleJson.ToJson(spec, names); + if (spec.RuleIndex is null) + { + var live = await ListNatRulesAsync(ct).ConfigureAwait(false); + body["rule_index"] = live.Select(r => r.Raw["rule_index"] is { } n ? n.GetValue() : 0).DefaultIfEmpty(0).Max() + 1; + } + + using var resp = await _session.SendAbsoluteAsync(HttpMethod.Post, NatUrl(), UnifiLegacySession.JsonBody(body.ToJsonString()), ct).ConfigureAwait(false); + return ParseNat(await ReadV2Async(resp, "nat", ct).ConfigureAwait(false) + ?? throw new UnifiLegacyException("create nat: ok but no object returned")); + } + + /// Replace a rule wholesale. Pass the full desired state, including its RuleIndex. + public async Task UpdateNatRuleAsync(string id, UnifiNatRuleSpec spec, UnifiNatNames names, CancellationToken ct = default) + { + var live = await RequireUserNatRuleAsync(id, "update", ct).ConfigureAwait(false); + var body = UnifiNatRuleJson.ToJson(spec, names); + body["_id"] = id; + // A PUT replaces the whole rule, so an omitted rule_index would be stored as null. + if (spec.RuleIndex is null && live.Raw["rule_index"] is { } keep) body["rule_index"] = keep.DeepClone(); + using var resp = await _session.SendAbsoluteAsync(HttpMethod.Put, NatUrl(id), UnifiLegacySession.JsonBody(body.ToJsonString()), ct).ConfigureAwait(false); + return ParseNat(await ReadV2Async(resp, "nat", ct).ConfigureAwait(false) ?? body); + } + + public async Task DeleteNatRuleAsync(string id, CancellationToken ct = default) + { + await RequireUserNatRuleAsync(id, "delete", ct).ConfigureAwait(false); + using var resp = await _session.SendAbsoluteAsync(HttpMethod.Delete, NatUrl(id), null, ct).ConfigureAwait(false); + await ReadV2Async(resp, "nat", ct).ConfigureAwait(false); // throws on failure + } + + // Fresh read, not a cached list: the guard must see the rule as it is now. + private async Task RequireUserNatRuleAsync(string id, string verb, CancellationToken ct) + { + ThrowUnlessPlainSegment(id); + var rule = (await ListNatRulesAsync(ct).ConfigureAwait(false)).FirstOrDefault(r => r.Id == id) + ?? throw new UnifiLegacyException($"{verb} nat: no rule with id '{id}'"); + if (rule.IsPredefined) + { + throw new UnifiLegacyException($"{verb} nat: '{rule.Name}' is a predefined rule and is not ours to change"); + } + + return rule; + } + + private static UnifiLiveNatRule ParseNat(JsonObject? r) + { + if (r is null || r["_id"]?.GetValue() is not { Length: > 0 } id) + { + throw new UnifiLegacyException("nat: a rule came back without an _id"); + } + + return new UnifiLiveNatRule(id, r["description"]?.GetValue() ?? "", r["is_predefined"]?.GetValue() ?? false, r); + } + + private Uri NatUrl(string? id = null) + { + var b = _session.Options.SiteV2Url.AbsoluteUri.TrimEnd('/'); + return new Uri(id is null ? $"{b}/nat" : $"{b}/nat/{id}"); + } + private Uri StaticDnsUrl(string? id = null) { var b = _session.Options.SiteV2Url.AbsoluteUri.TrimEnd('/'); diff --git a/src/UnifiSharp/Legacy/UnifiNatRule.cs b/src/UnifiSharp/Legacy/UnifiNatRule.cs new file mode 100644 index 0000000..4ccbd01 --- /dev/null +++ b/src/UnifiSharp/Legacy/UnifiNatRule.cs @@ -0,0 +1,74 @@ +using System.Text.Json.Nodes; + +namespace UnifiSharp.Legacy; + +public enum UnifiNatType { Dnat, Masquerade, Snat } + +/// +/// One side of a NAT match: a single IP, a range "a-b" or a CIDR, optionally with a port, and +/// optionally inverted ("everything except"). No address and no port means no filter. +/// +public sealed record UnifiNatFilter +{ + /// A single IP, a range written "first-last", or a CIDR. Null = any. + public string? Address { get; init; } + + /// A port or range, e.g. "53". Null = any. + public string? Port { get; init; } + + public bool InvertAddress { get; init; } + public bool InvertPort { get; init; } +} + +/// +/// Desired state of a custom NAT rule on the gateway (v2 site API: nat). Rules have no +/// name of their own, so is the controller's description and is what +/// callers reconcile by. Record equality is the drift check; leave null +/// on both sides when the order is not declared. +/// +public sealed record UnifiNatRuleSpec +{ + /// Written to description; the key a caller matches live rules by. + public required string Name { get; init; } + public required UnifiNatType Type { get; init; } + public bool Enabled { get; init; } = true; + + /// "all", "tcp_udp", "tcp" or "udp". + public string Protocol { get; init; } = "all"; + + /// Network NAME the traffic arrives on (in_interface); DNAT and SNAT. + public string? InNetwork { get; init; } + + /// Network NAME the traffic leaves on (out_interface); MASQUERADE. + public string? OutNetwork { get; init; } + + /// The address traffic is translated to (ip_address); DNAT and SNAT. + public string? TranslatedAddress { get; init; } + + /// The port traffic is translated to (port); DNAT and SNAT. + public string? TranslatedPort { get; init; } + + public UnifiNatFilter Source { get; init; } = new(); + public UnifiNatFilter Destination { get; init; } = new(); + public bool Logging { get; init; } + + /// + /// Position among NAT rules; the controller rejects a duplicate. Null = next free on create, + /// and the live rule's own index on update. + /// + public int? RuleIndex { get; init; } +} + +/// A NAT rule as the controller holds it. Predefined rules are the gateway's own. +public sealed record UnifiLiveNatRule(string Id, string Name, bool IsPredefined, JsonObject Raw); + +/// Network NAME to _id lookups for in_interface / out_interface. +public sealed record UnifiNatNames(IReadOnlyDictionary NetworkIds) +{ + // An id passes through: NetworkName hands back the raw id for a network it doesn't know by name. + internal string NetworkId(string name) => NetworkIds.TryGetValue(name, out var id) ? id + : NetworkIds.Values.Contains(name) ? name + : throw new ArgumentException($"unknown network '{name}' (known: {string.Join(", ", NetworkIds.Keys)})"); + + internal string NetworkName(string id) => NetworkIds.FirstOrDefault(kv => kv.Value == id).Key ?? id; +} diff --git a/src/UnifiSharp/Legacy/UnifiNatRuleJson.cs b/src/UnifiSharp/Legacy/UnifiNatRuleJson.cs new file mode 100644 index 0000000..3a4a256 --- /dev/null +++ b/src/UnifiSharp/Legacy/UnifiNatRuleJson.cs @@ -0,0 +1,117 @@ +using System.Text.Json.Nodes; + +namespace UnifiSharp.Legacy; + +/// +/// Maps to and from the v2 nat JSON. The body is always +/// complete because a PUT replaces the whole rule. +/// +public static class UnifiNatRuleJson +{ + public static JsonObject ToJson(UnifiNatRuleSpec s, UnifiNatNames names) + { + var body = new JsonObject + { + ["type"] = s.Type switch { UnifiNatType.Dnat => "DNAT", UnifiNatType.Masquerade => "MASQUERADE", _ => "SNAT" }, + ["description"] = s.Name, + ["enabled"] = s.Enabled, + ["ip_version"] = "IPV4", + ["protocol"] = s.Protocol, + ["source_filter"] = FilterJson(s.Source), + ["destination_filter"] = FilterJson(s.Destination), + ["logging"] = s.Logging, + ["exclude"] = false, + ["is_predefined"] = false, + ["pppoe_use_base_interface"] = false, + ["setting_preference"] = "manual", + }; + if (s.InNetwork is not null) body["in_interface"] = names.NetworkId(s.InNetwork); + if (s.OutNetwork is not null) body["out_interface"] = names.NetworkId(s.OutNetwork); + if (s.TranslatedAddress is not null) body["ip_address"] = s.TranslatedAddress; + if (s.TranslatedPort is not null) body["port"] = s.TranslatedPort; + if (s.RuleIndex is { } i) body["rule_index"] = i; + return body; + } + + public static UnifiNatRuleSpec FromJson(JsonObject r, UnifiNatNames names) + { + // ToJson writes these four at fixed values, so a live rule that differs would be rewritten + // by an update and read as "no drift". Refuse it rather than lose the difference. + RequireDefault(r, "ip_version", "IPV4"); + RequireDefault(r, "setting_preference", "manual"); + RequireFalse(r, "exclude"); + RequireFalse(r, "pppoe_use_base_interface"); + return Map(r, names); + } + + private static UnifiNatRuleSpec Map(JsonObject r, UnifiNatNames names) => new() + { + Name = Str(r, "description") ?? "", + Type = Str(r, "type") switch + { + "DNAT" => UnifiNatType.Dnat, + "MASQUERADE" => UnifiNatType.Masquerade, + "SNAT" => UnifiNatType.Snat, + var t => throw new ArgumentException($"unsupported NAT rule type '{t}'"), + }, + Enabled = r["enabled"]?.GetValue() ?? true, + Protocol = Str(r, "protocol") ?? "all", + InNetwork = Str(r, "in_interface") is { } i ? names.NetworkName(i) : null, + OutNetwork = Str(r, "out_interface") is { } o ? names.NetworkName(o) : null, + TranslatedAddress = Str(r, "ip_address"), + TranslatedPort = Str(r, "port"), + Source = FilterFrom(r["source_filter"] as JsonObject), + Destination = FilterFrom(r["destination_filter"] as JsonObject), + Logging = r["logging"]?.GetValue() ?? false, + RuleIndex = r["rule_index"] is { } n ? n.GetValue() : null, + }; + + private static JsonObject FilterJson(UnifiNatFilter f) + { + var any = f.Address is not null || f.Port is not null; + var o = new JsonObject + { + ["filter_type"] = any ? "ADDRESS_AND_PORT" : "NONE", + ["firewall_group_ids"] = new JsonArray(), + ["invert_address"] = f.InvertAddress, + ["invert_port"] = f.InvertPort, + }; + if (f.Address is not null) o["address"] = f.Address; + if (f.Port is not null) o["port"] = f.Port; + return o; + } + + private static UnifiNatFilter FilterFrom(JsonObject? f) + { + if (f is null) return new(); + // Only ADDRESS_AND_PORT is modelled; a filter on firewall groups or networks is not one + // this library can write back, so refuse it rather than report it as "no filter". + return Str(f, "filter_type") switch + { + "NONE" or null => new(), + "ADDRESS_AND_PORT" => new() + { + Address = NullIfEmpty(Str(f, "address")), + Port = NullIfEmpty(Str(f, "port")), + InvertAddress = f["invert_address"]?.GetValue() ?? false, + InvertPort = f["invert_port"]?.GetValue() ?? false, + }, + var t => throw new ArgumentException($"unsupported NAT filter type '{t}'"), + }; + } + + private static void RequireDefault(JsonObject r, string key, string expected) + { + if (Str(r, key) is { } v && v != expected) + throw new ArgumentException($"unsupported NAT rule {key} '{v}' (this library writes '{expected}')"); + } + + private static void RequireFalse(JsonObject r, string key) + { + if (r[key]?.GetValue() == true) + throw new ArgumentException($"unsupported NAT rule: {key} is true (this library writes false)"); + } + + private static string? Str(JsonObject o, string key) => o[key]?.GetValue(); + private static string? NullIfEmpty(string? s) => string.IsNullOrEmpty(s) ? null : s; +} diff --git a/tests/UnifiSharp.Tests/UnifiLegacyLiveTests.cs b/tests/UnifiSharp.Tests/UnifiLegacyLiveTests.cs index 2046fa2..fab73dd 100644 --- a/tests/UnifiSharp.Tests/UnifiLegacyLiveTests.cs +++ b/tests/UnifiSharp.Tests/UnifiLegacyLiveTests.cs @@ -100,6 +100,18 @@ public class UnifiLegacyLiveTests private readonly UnifiContainerFixture _fixture; public UnifiLegacyLiveTests(UnifiContainerFixture fixture) => _fixture = fixture; + [SkippableFact] + public async Task Nat_list_reaches_the_v2_endpoint_and_names_come_from_the_networks() + { + // The container has no gateway behind it, so it accepts no NAT rule (POST is a bare 500): + // the write path is covered by UnifiNatRuleTests against the shape the UCG returns. + Skip.If(_fixture.SkipReason is not null, _fixture.SkipReason); + var client = _fixture.Client; + + Assert.NotNull(await client.ListNatRulesAsync()); + Assert.NotEmpty((await client.GetNatNamesAsync()).NetworkIds); + } + [SkippableFact] public async Task PortForward_create_list_delete_roundtrip() { diff --git a/tests/UnifiSharp.Tests/UnifiNatRuleTests.cs b/tests/UnifiSharp.Tests/UnifiNatRuleTests.cs new file mode 100644 index 0000000..eb9b96f --- /dev/null +++ b/tests/UnifiSharp.Tests/UnifiNatRuleTests.cs @@ -0,0 +1,283 @@ +using System.Net; +using System.Text.Json.Nodes; +using UnifiSharp.Legacy; + +namespace UnifiSharp.Tests; + +#pragma warning disable CS0618 // UnifiLegacyClient is intentionally obsolete (ADR-0003) + +public class UnifiNatRuleTests +{ + private const string ConsumerId = "69449ac60a8b134de4bd2333"; + + private static readonly UnifiNatNames Names = new(new Dictionary { ["Consumer"] = ConsumerId }); + + // The two rules as the UCG (Network 10.6.106) returns them, per the Homelab Blocky session. + private const string LiveDnat = """ + {"_id":"6addb2ecc60ad991b79a5e63","type":"DNAT","description":"consumer-dns-redirect","enabled":true, + "ip_version":"IPV4","protocol":"tcp_udp","in_interface":"69449ac60a8b134de4bd2333","ip_address":"10.20.0.53", + "port":"53","rule_index":1, + "source_filter":{"filter_type":"ADDRESS_AND_PORT","address":"10.20.0.53-10.20.0.54","invert_address":true,"invert_port":false,"firewall_group_ids":[]}, + "destination_filter":{"filter_type":"ADDRESS_AND_PORT","address":"10.20.0.53-10.20.0.54","port":"53","invert_address":true,"invert_port":false,"firewall_group_ids":[]}, + "logging":false,"exclude":false,"is_predefined":false,"pppoe_use_base_interface":false,"setting_preference":"manual"} + """; + + private const string LiveMasquerade = """ + {"_id":"6addb2d9c60ad991b79a5e5f","type":"MASQUERADE","description":"consumer-dns-redirect-masq","enabled":true, + "ip_version":"IPV4","protocol":"tcp_udp","out_interface":"69449ac60a8b134de4bd2333","rule_index":2, + "source_filter":{"filter_type":"ADDRESS_AND_PORT","address":"10.20.0.0/16","invert_address":false,"invert_port":false,"firewall_group_ids":[]}, + "destination_filter":{"filter_type":"ADDRESS_AND_PORT","address":"10.20.0.53","port":"53","invert_address":false,"invert_port":false,"firewall_group_ids":[]}, + "logging":false,"exclude":false,"is_predefined":false,"pppoe_use_base_interface":false,"setting_preference":"manual"} + """; + + private static readonly UnifiNatRuleSpec DnatSpec = new() + { + Name = "consumer-dns-redirect", + Type = UnifiNatType.Dnat, + Protocol = "tcp_udp", + InNetwork = "Consumer", + TranslatedAddress = "10.20.0.53", + TranslatedPort = "53", + Source = new() { Address = "10.20.0.53-10.20.0.54", InvertAddress = true }, + Destination = new() { Address = "10.20.0.53-10.20.0.54", Port = "53", InvertAddress = true }, + RuleIndex = 1, + }; + + private static readonly UnifiNatRuleSpec MasqSpec = new() + { + Name = "consumer-dns-redirect-masq", + Type = UnifiNatType.Masquerade, + Protocol = "tcp_udp", + OutNetwork = "Consumer", + Source = new() { Address = "10.20.0.0/16" }, + Destination = new() { Address = "10.20.0.53", Port = "53" }, + RuleIndex = 2, + }; + + [Fact] + public void FromJson_reads_the_live_dnat_rule() + => Assert.Equal(DnatSpec, UnifiNatRuleJson.FromJson(JsonNode.Parse(LiveDnat)!.AsObject(), Names)); + + [Fact] + public void FromJson_reads_the_live_masquerade_rule() + => Assert.Equal(MasqSpec, UnifiNatRuleJson.FromJson(JsonNode.Parse(LiveMasquerade)!.AsObject(), Names)); + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void ToJson_then_FromJson_round_trips(bool dnat) + { + var spec = dnat ? DnatSpec : MasqSpec; + Assert.Equal(spec, UnifiNatRuleJson.FromJson(UnifiNatRuleJson.ToJson(spec, Names), Names)); + } + + [Fact] + public void ToJson_resolves_network_names_to_ids_and_omits_what_masquerade_has_no_use_for() + { + var body = UnifiNatRuleJson.ToJson(MasqSpec, Names); + Assert.Equal(ConsumerId, body["out_interface"]!.GetValue()); + Assert.Null(body["in_interface"]); + Assert.Null(body["ip_address"]); + Assert.Null(body["port"]); + Assert.Equal("consumer-dns-redirect-masq", body["description"]!.GetValue()); + Assert.Equal("MASQUERADE", body["type"]!.GetValue()); + } + + [Fact] + public void ToJson_writes_a_filter_with_no_address_or_port_as_NONE() + { + var body = UnifiNatRuleJson.ToJson(DnatSpec with { Source = new() }, Names); + Assert.Equal("NONE", body["source_filter"]!["filter_type"]!.GetValue()); + Assert.Null(body["source_filter"]!["address"]); + } + + [Fact] + public void ToJson_refuses_an_unknown_network() + => Assert.Throws(() => UnifiNatRuleJson.ToJson(DnatSpec with { InNetwork = "Nope" }, Names)); + + [Fact] + public void FromJson_refuses_a_filter_it_cannot_write_back() + { + var rule = JsonNode.Parse(LiveDnat)!.AsObject(); + rule["source_filter"]!["filter_type"] = "FIREWALL_GROUPS"; + Assert.Throws(() => UnifiNatRuleJson.FromJson(rule, Names)); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void Live_to_spec_to_json_keeps_every_field_a_live_rule_carries(bool dnat) + { + // Spec -> JSON -> spec can't see a field ToJson drops; live -> spec -> JSON can. + var live = JsonNode.Parse(dnat ? LiveDnat : LiveMasquerade)!.AsObject(); + var back = UnifiNatRuleJson.ToJson(UnifiNatRuleJson.FromJson(live, Names), Names); + live.Remove("_id"); + Assert.Equal(Sorted(live).ToJsonString(), Sorted(back).ToJsonString()); + } + + [Theory] + [InlineData("ip_version", "IPV6")] + [InlineData("setting_preference", "auto")] + public void FromJson_refuses_a_field_it_would_otherwise_rewrite(string key, string value) + { + var rule = JsonNode.Parse(LiveDnat)!.AsObject(); + rule[key] = value; + Assert.Throws(() => UnifiNatRuleJson.FromJson(rule, Names)); + } + + [Theory] + [InlineData("exclude")] + [InlineData("pppoe_use_base_interface")] + public void FromJson_refuses_a_flag_it_would_otherwise_rewrite(string key) + { + var rule = JsonNode.Parse(LiveDnat)!.AsObject(); + rule[key] = true; + Assert.Throws(() => UnifiNatRuleJson.FromJson(rule, Names)); + } + + [Fact] + public void An_unknown_network_id_round_trips_as_itself() + { + var rule = JsonNode.Parse(LiveDnat)!.AsObject(); + rule["in_interface"] = "abc"; + // known only by value elsewhere in the lookup: the id passes through, an unknown one still throws + var names = new UnifiNatNames(new Dictionary { ["Consumer"] = ConsumerId, ["Other"] = "abc" }); + Assert.Equal("Other", UnifiNatRuleJson.FromJson(rule, names).InNetwork); + Assert.Equal("abc", UnifiNatRuleJson.ToJson(UnifiNatRuleJson.FromJson(rule, names), names)["in_interface"]!.GetValue()); + Assert.Throws(() => UnifiNatRuleJson.ToJson(DnatSpec with { InNetwork = "zzz" }, names)); + } + + [Fact] + public async Task Update_keeps_the_live_rule_index_when_the_spec_has_none() + { + var h = new NatHandler($"[{LiveDnat}]"); + using var c = h.Client(); + await c.UpdateNatRuleAsync("6addb2ecc60ad991b79a5e63", DnatSpec with { RuleIndex = null }, Names); + var put = h.Requests.Single(r => r.Method == HttpMethod.Put); + Assert.Equal(1, JsonNode.Parse(put.Body!)!["rule_index"]!.GetValue()); + } + + private static JsonObject Sorted(JsonObject o) => new(o.OrderBy(kv => kv.Key, StringComparer.Ordinal) + .Select(kv => KeyValuePair.Create(kv.Key, kv.Value is JsonObject c ? Sorted(c) : kv.Value?.DeepClone()))); + + [Fact] + public void Equality_notices_an_inverted_match_flipping() + => Assert.NotEqual(DnatSpec, DnatSpec with { Source = DnatSpec.Source with { InvertAddress = false } }); + + [Fact] + public async Task List_returns_rules_and_flags_predefined_ones() + { + var h = new NatHandler($"[{LiveDnat},{LiveMasquerade.Replace("\"is_predefined\":false", "\"is_predefined\":true")}]"); + using var c = h.Client(); + var rules = await c.ListNatRulesAsync(); + Assert.Equal(["consumer-dns-redirect", "consumer-dns-redirect-masq"], rules.Select(r => r.Name)); + Assert.Equal([false, true], rules.Select(r => r.IsPredefined)); + Assert.EndsWith("/proxy/network/v2/api/site/default/nat", h.Requests[0].Uri.AbsolutePath); + } + + [Fact] + public async Task Create_picks_the_next_free_rule_index_when_the_spec_has_none() + { + var h = new NatHandler($"[{LiveDnat},{LiveMasquerade}]"); + using var c = h.Client(); + await c.CreateNatRuleAsync(DnatSpec with { Name = "third", RuleIndex = null }, Names); + var post = h.Requests.Single(r => r.Method == HttpMethod.Post); + Assert.Equal(3, JsonNode.Parse(post.Body!)!["rule_index"]!.GetValue()); + } + + [Fact] + public async Task Create_keeps_a_declared_rule_index_and_does_not_list_first() + { + var h = new NatHandler("[]"); + using var c = h.Client(); + await c.CreateNatRuleAsync(DnatSpec, Names); + Assert.Equal([HttpMethod.Post], h.Requests.Select(r => r.Method)); + Assert.Equal(1, JsonNode.Parse(h.Requests[0].Body!)!["rule_index"]!.GetValue()); + } + + [Fact] + public async Task Update_sends_the_whole_rule_with_its_id() + { + var h = new NatHandler($"[{LiveDnat}]"); + using var c = h.Client(); + await c.UpdateNatRuleAsync("6addb2ecc60ad991b79a5e63", DnatSpec with { Enabled = false }, Names); + var put = h.Requests.Single(r => r.Method == HttpMethod.Put); + Assert.EndsWith("/nat/6addb2ecc60ad991b79a5e63", put.Uri.AbsolutePath); + var body = JsonNode.Parse(put.Body!)!.AsObject(); + Assert.Equal("6addb2ecc60ad991b79a5e63", body["_id"]!.GetValue()); + Assert.False(body["enabled"]!.GetValue()); + Assert.Equal("10.20.0.53", body["ip_address"]!.GetValue()); + } + + [Fact] + public async Task Delete_removes_a_user_rule() + { + var h = new NatHandler($"[{LiveDnat}]"); + using var c = h.Client(); + await c.DeleteNatRuleAsync("6addb2ecc60ad991b79a5e63"); + Assert.Contains(h.Requests, r => r.Method == HttpMethod.Delete && r.Uri.AbsolutePath.EndsWith("/nat/6addb2ecc60ad991b79a5e63")); + } + + [Fact] + public async Task Delete_and_update_refuse_a_predefined_rule_without_writing() + { + var predefined = LiveDnat.Replace("\"is_predefined\":false", "\"is_predefined\":true"); + var h = new NatHandler($"[{predefined}]"); + using var c = h.Client(); + await Assert.ThrowsAsync(() => c.DeleteNatRuleAsync("6addb2ecc60ad991b79a5e63")); + await Assert.ThrowsAsync(() => c.UpdateNatRuleAsync("6addb2ecc60ad991b79a5e63", DnatSpec, Names)); + Assert.All(h.Requests, r => Assert.Equal(HttpMethod.Get, r.Method)); + } + + [Fact] + public async Task Delete_and_update_refuse_an_id_that_is_not_on_the_controller() + { + var h = new NatHandler("[]"); + using var c = h.Client(); + await Assert.ThrowsAsync(() => c.DeleteNatRuleAsync("deadbeef")); + await Assert.ThrowsAsync(() => c.UpdateNatRuleAsync("deadbeef", DnatSpec, Names)); + Assert.All(h.Requests, r => Assert.Equal(HttpMethod.Get, r.Method)); + } + + [Theory] + [InlineData("../x")] + [InlineData("a?b")] + public async Task Delete_refuses_an_id_that_is_not_a_plain_path_segment(string id) + { + var h = new NatHandler("[]"); + using var c = h.Client(); + await Assert.ThrowsAsync(() => c.DeleteNatRuleAsync(id)); + Assert.Empty(h.Requests); + } + + [Fact] + public async Task Create_surfaces_the_controllers_message_on_a_400() + { + var h = new NatHandler("[]", postStatus: HttpStatusCode.BadRequest, postBody: """{"message":"api.err.NatRuleInvalidParameters: duplicate rule_index"}"""); + using var c = h.Client(); + var ex = await Assert.ThrowsAsync(() => c.CreateNatRuleAsync(DnatSpec, Names)); + Assert.Contains("duplicate rule_index", ex.Message); + } + + // GET nat answers the canned list; POST/PUT echo the body (POST adds an _id); DELETE is 200 empty. + private sealed class NatHandler(string list, HttpStatusCode postStatus = HttpStatusCode.OK, string? postBody = null) : HttpMessageHandler + { + public List<(HttpMethod Method, Uri Uri, string? Body)> Requests { get; } = []; + + public UnifiLegacyClient Client() => new(new UnifiLegacySession( + new UnifiLegacyOptions { BaseUrl = new Uri("https://gw.lan:11443/proxy/network/api/s/default"), ApiKey = "k" }, this), ownsSession: true); + + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken ct) + { + var body = request.Content is null ? null : await request.Content.ReadAsStringAsync(ct); + Requests.Add((request.Method, request.RequestUri!, body)); + if (request.Method == HttpMethod.Get) return new(HttpStatusCode.OK) { Content = new StringContent(list) }; + if (request.Method == HttpMethod.Delete) return new(HttpStatusCode.OK) { Content = new StringContent("") }; + if (request.Method == HttpMethod.Post && postStatus != HttpStatusCode.OK) + return new(postStatus) { Content = new StringContent(postBody ?? "") }; + var echo = JsonNode.Parse(body!)!.AsObject(); + echo["_id"] ??= "newid0000000000000000aa"; + return new(HttpStatusCode.OK) { Content = new StringContent(echo.ToJsonString()) }; + } + } +} From 1c7ad30422d2e99edcfbb060856b097f02bfb88d Mon Sep 17 00:00:00 2001 From: Chrison Simtian Date: Sun, 8 Nov 2026 13:23:51 +1300 Subject: [PATCH 2/2] Check live NAT rules survive a spec round trip --- tests/UnifiSharp.Tests/UnifiLegacyLiveTests.cs | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/tests/UnifiSharp.Tests/UnifiLegacyLiveTests.cs b/tests/UnifiSharp.Tests/UnifiLegacyLiveTests.cs index fab73dd..beae47b 100644 --- a/tests/UnifiSharp.Tests/UnifiLegacyLiveTests.cs +++ b/tests/UnifiSharp.Tests/UnifiLegacyLiveTests.cs @@ -49,6 +49,23 @@ public async Task ApiKey_auth_can_read_networks_without_a_session_login() Assert.Contains(networks, n => !string.IsNullOrEmpty(n.Id)); } + [SkippableFact] + public async Task Every_live_nat_rule_maps_to_a_spec_and_back_unchanged() + { + Skip.If(_fixture.Client is null, "No UniFi env — skipping live read test."); + Skip.IfNot(_fixture.UsesApiKey, "Not in API-key mode — this test covers the X-API-KEY path."); + + var names = await _fixture.Client!.GetNatNamesAsync(); + foreach (var rule in await _fixture.Client.ListNatRulesAsync()) + { + // Predefined rules are the gateway's own and may use shapes this library refuses. + if (rule.IsPredefined) continue; + var back = UnifiNatRuleJson.ToJson(UnifiNatRuleJson.FromJson(rule.Raw, names), names); + foreach (var (key, value) in back) + Assert.True(JsonNode.DeepEquals(value, rule.Raw[key]), $"'{rule.Name}': {key} differs after a round trip"); + } + } + [SkippableFact] public async Task ApiKey_auth_can_read_known_clients_and_their_reservations() {