b711b71f92
The rule set is now the outermost group: it holds conditions of its own beside nested groups, with its own All/Any and Not, and groups nest to eight levels. Rule sets stored in the older two-level shape (blocks of conditions) read, save and evaluate exactly as before; rules stay JSON in RulesJson, so no migration. Saving or previewing a rule checks it by row path: nesting depth, a 200-condition cap, a field on every row, patterns compiled with .NET regex semantics and CIDR ranges that parse. The field catalogue gains a type, fixed choices and a short description for the console's picker. GET /api/groups/fields/values?field=&prefix=&limit= returns a field's distinct values with device counts (groups.manage, limited to the caller's device scope, 25 by default and 100 at most). The preview and members endpoints now also stay inside the caller's device scope. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
243 lines
13 KiB
C#
243 lines
13 KiB
C#
using System.Text.Json.Nodes;
|
|
using Shared.Contracts.Models;
|
|
using Shared.Contracts.Serialization;
|
|
using Shared.Infrastructure.Grouping;
|
|
using Xunit;
|
|
|
|
namespace Shared.Tests;
|
|
|
|
/// <summary>
|
|
/// Rules as the condition builder writes them now (conditions and groups at
|
|
/// every level, a Not on the rule itself), and proof that rule sets saved in
|
|
/// the older two-level shape read, save and match exactly as before.
|
|
/// </summary>
|
|
public class RuleNestingTests
|
|
{
|
|
/// <summary>Rule sets as earlier versions stored them: the rule holds only blocks, each block only conditions.</summary>
|
|
public static readonly TheoryData<string> LegacyRuleSets =
|
|
[
|
|
// The seeded platform groups.
|
|
"""{"combine":"and","groups":[{"combine":"and","conditions":[{"field":"os.platform","operator":"equals","value":"windows","negate":false}],"negate":false}]}""",
|
|
"""{"combine":"and","groups":[{"combine":"and","conditions":[{"field":"os.platform","operator":"equals","value":"windows","negate":false},{"field":"os.caption","operator":"notContains","value":"Server","negate":false}],"negate":false}]}""",
|
|
// The development seed: (Dell or Lenovo) and (16 GB and a workstation tag).
|
|
"""{"combine":"and","groups":[{"combine":"or","conditions":[{"field":"manufacturer","operator":"equals","value":"Dell Inc.","negate":false},{"field":"manufacturer","operator":"equals","value":"LENOVO","negate":false}],"negate":false},{"combine":"and","conditions":[{"field":"memory.totalGb","operator":"greaterOrEqual","value":"16","negate":false},{"field":"tags","operator":"contains","value":"workstation","negate":false}],"negate":false}]}""",
|
|
// Blocks combined with Any, a negated block, a negated condition, lists and ranges.
|
|
"""{"combine":"or","groups":[{"combine":"and","conditions":[{"field":"status","operator":"equals","value":"offline","negate":false}],"negate":true},{"combine":"or","conditions":[{"field":"hostname","operator":"in","value":"PC-001, PC-002;KIOSK-9","negate":false},{"field":"network.ipv4","operator":"inCidr","value":"10.20.0.0/16, 192.168.1.0/24","negate":true}],"negate":false}]}""",
|
|
// An empty block among others, and a value-less operator.
|
|
"""{"combine":"and","groups":[{"combine":"and","conditions":[],"negate":false},{"combine":"and","conditions":[{"field":"tags","operator":"exists","negate":false}],"negate":false}]}""",
|
|
"""{"combine":"or","groups":[{"combine":"and","conditions":[],"negate":false},{"combine":"and","conditions":[{"field":"tags","operator":"notExists","negate":false}],"negate":false}]}""",
|
|
// No blocks at all, and a block nested inside a block (the contract always allowed it).
|
|
"""{"combine":"and","groups":[]}""",
|
|
"""{"combine":"and"}""",
|
|
"""{"combine":"and","groups":[{"combine":"and","conditions":[{"field":"manufacturer","operator":"startsWith","value":"Dell","negate":false}],"groups":[{"combine":"or","conditions":[{"field":"cpu.cores","operator":"greaterThan","value":"4","negate":false},{"field":"agentVersion","operator":"lessThan","value":"1.4","negate":false}],"negate":true}],"negate":false}]}""",
|
|
];
|
|
|
|
[Theory]
|
|
[MemberData(nameof(LegacyRuleSets))]
|
|
public void ALegacyRuleSetMatchesTheSameDevicesAsBefore(string json)
|
|
{
|
|
var rules = JsonDefaults.Deserialize<GroupRuleSet>(json)!;
|
|
|
|
foreach (var (name, bag) in Fleet())
|
|
{
|
|
Assert.True(LegacyMatches(rules, bag) == RuleEvaluator.Matches(rules, bag), $"{name}: {json}");
|
|
}
|
|
}
|
|
|
|
[Theory]
|
|
[MemberData(nameof(LegacyRuleSets))]
|
|
public void ALegacyRuleSetSavesBackWithoutLoss(string json)
|
|
{
|
|
var rules = JsonDefaults.Deserialize<GroupRuleSet>(json)!;
|
|
var saved = JsonNode.Parse(JsonDefaults.Serialize(rules))!.AsObject();
|
|
|
|
// Saving adds only the rule's own Not, off; every block and condition is kept as it was.
|
|
Assert.False(saved["negate"]!.GetValue<bool>());
|
|
Assert.Null(saved["conditions"]);
|
|
saved.Remove("negate");
|
|
Assert.True(JsonNode.DeepEquals(JsonNode.Parse(json), saved), saved.ToJsonString());
|
|
|
|
var again = JsonDefaults.Deserialize<GroupRuleSet>(saved.ToJsonString())!;
|
|
foreach (var (_, bag) in Fleet())
|
|
{
|
|
Assert.Equal(RuleEvaluator.Matches(rules, bag), RuleEvaluator.Matches(again, bag));
|
|
}
|
|
}
|
|
|
|
[Theory]
|
|
[MemberData(nameof(LegacyRuleSets))]
|
|
public void ALegacyRuleSetIsStillValid(string json)
|
|
=> Assert.Empty(RuleValidator.Validate(JsonDefaults.Deserialize<GroupRuleSet>(json)));
|
|
|
|
[Fact]
|
|
public void TheRuleHoldsConditionsOfItsOwn()
|
|
{
|
|
var rules = new GroupRuleSet(
|
|
RuleCombine.And,
|
|
Groups: [new RuleGroup(RuleCombine.Or, [Is("status", "offline"), Is("tags", "kiosk")])],
|
|
Conditions: [Is("manufacturer", "Dell Inc.")]);
|
|
|
|
Assert.True(RuleEvaluator.Matches(rules, Bag(tags: ["kiosk"])));
|
|
Assert.False(RuleEvaluator.Matches(rules, Bag(tags: ["finance"])));
|
|
Assert.False(RuleEvaluator.Matches(rules, Bag(manufacturer: "LENOVO", tags: ["kiosk"])));
|
|
// Conditions alone, no groups.
|
|
Assert.True(RuleEvaluator.Matches(new GroupRuleSet(Conditions: [Is("hostname", "PC-001")]), Bag()));
|
|
}
|
|
|
|
[Fact]
|
|
public void NotOnTheRuleInvertsIt()
|
|
{
|
|
var rules = new GroupRuleSet(RuleCombine.Or, Conditions: [Is("status", "offline"), Is("tags", "kiosk")], Negate: true);
|
|
|
|
Assert.True(RuleEvaluator.Matches(rules, Bag(tags: ["finance"])));
|
|
Assert.False(RuleEvaluator.Matches(rules, Bag(tags: ["kiosk"])));
|
|
}
|
|
|
|
[Fact]
|
|
public void AnEmptyRuleMatchesNothingEvenNegated()
|
|
{
|
|
Assert.False(RuleEvaluator.Matches(new GroupRuleSet(Negate: true), Bag()));
|
|
Assert.False(RuleEvaluator.Matches(new GroupRuleSet(Groups: [new RuleGroup(Negate: true)]), Bag()));
|
|
}
|
|
|
|
[Fact]
|
|
public void GroupsNestToTheLimitAndEvaluateAtEveryLevel()
|
|
{
|
|
// hostname = PC-001 and not (tags has lab or (manufacturer = LENOVO and (cores > 16 or status = offline)))
|
|
var innermost = new RuleGroup(RuleCombine.Or, [
|
|
new RuleCondition("cpu.cores", RuleOperator.GreaterThan, "16"),
|
|
Is("status", "offline"),
|
|
]);
|
|
var middle = new RuleGroup(RuleCombine.And, [Is("manufacturer", "LENOVO")], [innermost]);
|
|
var outer = new RuleGroup(RuleCombine.Or, [Is("tags", "lab")], [middle], Negate: true);
|
|
var rules = new GroupRuleSet(RuleCombine.And, [outer], [Is("hostname", "PC-001")]);
|
|
|
|
Assert.True(RuleEvaluator.Matches(rules, Bag()));
|
|
Assert.False(RuleEvaluator.Matches(rules, Bag(tags: ["lab"])));
|
|
Assert.True(RuleEvaluator.Matches(rules, Bag(manufacturer: "LENOVO")));
|
|
Assert.False(RuleEvaluator.Matches(rules, Bag(manufacturer: "LENOVO", status: DeviceStatus.Offline)));
|
|
Assert.Empty(RuleValidator.Validate(rules));
|
|
}
|
|
|
|
[Fact]
|
|
public void NestingPastTheLimitIsRefusedWhereItHappens()
|
|
{
|
|
// The rule is level 1; each group nests one level deeper, always as row 2 (after one condition).
|
|
RuleGroup Level(int remaining)
|
|
=> new(RuleCombine.And, [Is("hostname", "PC-001")], remaining > 0 ? [Level(remaining - 1)] : null);
|
|
|
|
var atLimit = new GroupRuleSet(RuleCombine.And, [Level(GroupRuleLimits.MaxDepth - 2)], [Is("hostname", "PC-001")]);
|
|
var pastLimit = new GroupRuleSet(RuleCombine.And, [Level(GroupRuleLimits.MaxDepth - 1)], [Is("hostname", "PC-001")]);
|
|
|
|
Assert.Empty(RuleValidator.Validate(atLimit));
|
|
var errors = RuleValidator.Validate(pastLimit);
|
|
var path = string.Join('.', Enumerable.Repeat("2", GroupRuleLimits.MaxDepth));
|
|
Assert.Equal([path], errors.Keys);
|
|
Assert.Contains($"{GroupRuleLimits.MaxDepth} levels", errors[path][0]);
|
|
}
|
|
|
|
[Fact]
|
|
public void RowsAreNumberedConditionsFirstThenGroups()
|
|
{
|
|
var rules = new GroupRuleSet(
|
|
RuleCombine.And,
|
|
Groups: [new RuleGroup(RuleCombine.And, [Is("hostname", "a"), new RuleCondition(" ", RuleOperator.Equals, "b")])],
|
|
Conditions: [new RuleCondition("", RuleOperator.Exists)]);
|
|
|
|
var errors = RuleValidator.Validate(rules);
|
|
|
|
Assert.Equal(["1", "2.2"], errors.Keys.Order());
|
|
Assert.Equal("Choose a field.", errors["2.2"][0]);
|
|
}
|
|
|
|
[Theory]
|
|
[InlineData(RuleOperator.Regex, "^PC-\\d+$", true)]
|
|
[InlineData(RuleOperator.Regex, "(?i)^pc-(?<n>\\d+)$", true)] // .NET syntax a browser would refuse
|
|
[InlineData(RuleOperator.Regex, "^PC-(\\d+$", false)]
|
|
[InlineData(RuleOperator.Regex, "[z-a]", false)]
|
|
[InlineData(RuleOperator.InCidr, "10.0.0.0/8, 192.168.1.7", true)]
|
|
[InlineData(RuleOperator.InCidr, "10.30.9.27/24", true)] // host bits are tolerated, as evaluation does
|
|
[InlineData(RuleOperator.NotInCidr, "fd00::/8", true)]
|
|
[InlineData(RuleOperator.InCidr, "10.0.0.0/33", false)]
|
|
[InlineData(RuleOperator.InCidr, "10.0.0.0/8, office", false)]
|
|
[InlineData(RuleOperator.NotInCidr, " ", false)]
|
|
[InlineData(RuleOperator.Contains, "(", true)] // only patterns are read as patterns
|
|
public void AValueTheOperatorCannotReadIsRefused(RuleOperator op, string value, bool valid)
|
|
{
|
|
var rules = new GroupRuleSet(Conditions: [new RuleCondition("network.ipv4", op, value)]);
|
|
|
|
var errors = RuleValidator.Validate(rules);
|
|
|
|
Assert.Equal(valid, errors.Count == 0);
|
|
if (!valid)
|
|
{
|
|
Assert.Equal(["1"], errors.Keys);
|
|
}
|
|
}
|
|
|
|
[Fact]
|
|
public void TooManyConditionsAreRefusedOnTheRule()
|
|
{
|
|
var many = Enumerable.Range(0, GroupRuleLimits.MaxConditions + 1).Select(i => Is("hostname", $"PC-{i}")).ToList();
|
|
var rules = new GroupRuleSet(RuleCombine.Or, [new RuleGroup(RuleCombine.Or, many)]);
|
|
|
|
Assert.Equal([""], RuleValidator.Validate(rules).Keys);
|
|
}
|
|
|
|
[Fact]
|
|
public void EveryFieldDescribesItsType()
|
|
{
|
|
Assert.All(GroupFields.All, f => Assert.False(string.IsNullOrWhiteSpace(f.Description)));
|
|
Assert.All(GroupFields.All.Where(f => f.Type is GroupFieldType.Choice or GroupFieldType.Boolean),
|
|
f => Assert.NotEmpty(f.Choices!));
|
|
Assert.All(GroupFields.All.Where(f => f.Type == GroupFieldType.Number), f => Assert.True(f.Numeric));
|
|
Assert.Equal(GroupFields.All.Count, GroupFields.All.Select(f => f.Field).Distinct(StringComparer.OrdinalIgnoreCase).Count());
|
|
Assert.Same(GroupFields.All.Single(f => f.Field == "os.platform"), GroupFields.Find("OS.Platform"));
|
|
}
|
|
|
|
/// <summary>The rule set's evaluation before the rule held conditions of its own: its blocks, combined.</summary>
|
|
private static bool LegacyMatches(GroupRuleSet ruleSet, DeviceFieldBag fields)
|
|
{
|
|
var groups = ruleSet.Groups;
|
|
if (groups is null || groups.Count == 0)
|
|
{
|
|
return false;
|
|
}
|
|
|
|
var results = groups.Select(g => RuleEvaluator.Matches(g, fields));
|
|
return ruleSet.Combine == RuleCombine.Or ? results.Any(r => r) : results.All(r => r);
|
|
}
|
|
|
|
private static RuleCondition Is(string field, string value) => new(field, RuleOperator.Equals, value);
|
|
|
|
private static IEnumerable<(string Name, DeviceFieldBag Bag)> Fleet()
|
|
{
|
|
yield return ("dell workstation", Bag(tags: ["workstation"]));
|
|
yield return ("lenovo offline", Bag(manufacturer: "LENOVO", status: DeviceStatus.Offline));
|
|
yield return ("server", Bag(os: "Windows Server 2022 Datacenter", memoryBytes: 8L << 30));
|
|
yield return ("ubuntu kiosk", Bag(os: "Ubuntu 24.04 LTS", hostname: "KIOSK-9", tags: ["kiosk"], ips: ["192.168.1.40"]));
|
|
yield return ("hp untagged", Bag(manufacturer: "HP", hostname: "PC-002", cores: 2, ips: ["172.16.0.5"]));
|
|
yield return ("no inventory", DeviceFieldBag.Build("c9", "NEW-1", DeviceStatus.Stale, "1.3.0", null, null, "Windows 11 Pro"));
|
|
}
|
|
|
|
private static DeviceFieldBag Bag(
|
|
string manufacturer = "Dell Inc.",
|
|
string os = "Windows 11 Pro",
|
|
int cores = 8,
|
|
long memoryBytes = 34_359_738_368,
|
|
string[]? ips = null,
|
|
DeviceStatus status = DeviceStatus.Online,
|
|
string[]? tags = null,
|
|
string hostname = "PC-001")
|
|
=> DeviceFieldBag.Build("c1", hostname, status, "1.4.2", tags, new InventoryReport(
|
|
new InventoryIdentity("c1", hostname, manufacturer, "OptiPlex 7090", "SN1", "1.2.3", "BB1", "CORP", true, "x64-based PC"),
|
|
new InventoryOs(os, "10.0.26100", "26100", "64-bit", null, null, "Professional"),
|
|
new InventoryCpu("Intel Core i7", cores * 2, cores),
|
|
[],
|
|
memoryBytes,
|
|
[new InventoryDisk("SSD", "S1", 1_000_000_000_000, "NVMe")],
|
|
[new InventoryVolume("C:", "NTFS", 1_000_000_000_000, 500_000_000_000)],
|
|
[new InventoryNetworkAdapter("NIC", "00:11:22:33:44:55", ips ?? ["10.20.4.14"], [], ["10.20.0.1"], ["10.20.0.10"], InterfaceName: "eth0")],
|
|
DateTimeOffset.UtcNow));
|
|
}
|