Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/<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,
Expand Down
86 changes: 86 additions & 0 deletions src/UnifiSharp/Legacy/UnifiLegacyClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,92 @@ public async Task DeleteStaticDnsAsync(string id, CancellationToken ct = default
await ReadV2Async<JsonElement?>(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<IReadOnlyList<UnifiLiveNatRule>> ListNatRulesAsync(CancellationToken ct = default)
{
using var resp = await _session.SendAbsoluteAsync(HttpMethod.Get, NatUrl(), null, ct).ConfigureAwait(false);
var rows = await ReadV2Async<IReadOnlyList<JsonObject?>>(resp, "nat", ct).ConfigureAwait(false) ?? [];
return rows.Select(ParseNat).ToList();
}

/// <summary>Network name → <c>_id</c>, the form <c>in_interface</c> / <c>out_interface</c> take.</summary>
public async Task<UnifiNatNames> 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<UnifiLiveNatRule> 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<int>() : 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<JsonObject>(resp, "nat", ct).ConfigureAwait(false)
?? throw new UnifiLegacyException("create nat: ok but no object returned"));
}

/// <summary>Replace a rule wholesale. Pass the full desired state, including its RuleIndex.</summary>
public async Task<UnifiLiveNatRule> 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<JsonObject>(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<JsonElement?>(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<UnifiLiveNatRule> 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<string>() is not { Length: > 0 } id)
{
throw new UnifiLegacyException("nat: a rule came back without an _id");
}

return new UnifiLiveNatRule(id, r["description"]?.GetValue<string>() ?? "", r["is_predefined"]?.GetValue<bool>() ?? 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('/');
Expand Down
74 changes: 74 additions & 0 deletions src/UnifiSharp/Legacy/UnifiNatRule.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
using System.Text.Json.Nodes;

namespace UnifiSharp.Legacy;

public enum UnifiNatType { Dnat, Masquerade, Snat }

/// <summary>
/// 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.
/// </summary>
public sealed record UnifiNatFilter
{
/// <summary>A single IP, a range written "first-last", or a CIDR. Null = any.</summary>
public string? Address { get; init; }

/// <summary>A port or range, e.g. "53". Null = any.</summary>
public string? Port { get; init; }

public bool InvertAddress { get; init; }
public bool InvertPort { get; init; }
}

/// <summary>
/// Desired state of a custom NAT rule on the gateway (v2 site API: <c>nat</c>). Rules have no
/// name of their own, so <see cref="Name"/> is the controller's <c>description</c> and is what
/// callers reconcile by. Record equality is the drift check; leave <see cref="RuleIndex"/> null
/// on both sides when the order is not declared.
/// </summary>
public sealed record UnifiNatRuleSpec
{
/// <summary>Written to <c>description</c>; the key a caller matches live rules by.</summary>
public required string Name { get; init; }
public required UnifiNatType Type { get; init; }
public bool Enabled { get; init; } = true;

/// <summary>"all", "tcp_udp", "tcp" or "udp".</summary>
public string Protocol { get; init; } = "all";

/// <summary>Network NAME the traffic arrives on (<c>in_interface</c>); DNAT and SNAT.</summary>
public string? InNetwork { get; init; }

/// <summary>Network NAME the traffic leaves on (<c>out_interface</c>); MASQUERADE.</summary>
public string? OutNetwork { get; init; }

/// <summary>The address traffic is translated to (<c>ip_address</c>); DNAT and SNAT.</summary>
public string? TranslatedAddress { get; init; }

/// <summary>The port traffic is translated to (<c>port</c>); DNAT and SNAT.</summary>
public string? TranslatedPort { get; init; }

public UnifiNatFilter Source { get; init; } = new();
public UnifiNatFilter Destination { get; init; } = new();
public bool Logging { get; init; }

/// <summary>
/// Position among NAT rules; the controller rejects a duplicate. Null = next free on create,
/// and the live rule's own index on update.
/// </summary>
public int? RuleIndex { get; init; }
}

/// <summary>A NAT rule as the controller holds it. Predefined rules are the gateway's own.</summary>
public sealed record UnifiLiveNatRule(string Id, string Name, bool IsPredefined, JsonObject Raw);

/// <summary>Network NAME to <c>_id</c> lookups for <c>in_interface</c> / <c>out_interface</c>.</summary>
public sealed record UnifiNatNames(IReadOnlyDictionary<string, string> 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;
}
117 changes: 117 additions & 0 deletions src/UnifiSharp/Legacy/UnifiNatRuleJson.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
using System.Text.Json.Nodes;

namespace UnifiSharp.Legacy;

/// <summary>
/// Maps <see cref="UnifiNatRuleSpec"/> to and from the v2 <c>nat</c> JSON. The body is always
/// complete because a PUT replaces the whole rule.
/// </summary>
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<bool>() ?? 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<bool>() ?? false,
RuleIndex = r["rule_index"] is { } n ? n.GetValue<int>() : 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<bool>() ?? false,
InvertPort = f["invert_port"]?.GetValue<bool>() ?? 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<bool>() == 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<string>();
private static string? NullIfEmpty(string? s) => string.IsNullOrEmpty(s) ? null : s;
}
29 changes: 29 additions & 0 deletions tests/UnifiSharp.Tests/UnifiLegacyLiveTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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()
{
Expand Down Expand Up @@ -100,6 +117,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()
{
Expand Down
Loading
Loading