Files
ScadaBridge/tests/ZB.MOM.WW.ScadaBridge.CLI.Tests/CommandTreeTests.cs
T
Joseph Doherty f33f25a10b fix(auth+cli): fail-closed site-scope gate (row 98); case-insensitive audit filter values with a strict server-side check (row 99)
Register row 98 — the site-scope authorization gate was FAIL-OPEN on an
unresolvable target. The resolve-then-check shape was written as
`if (target != null) EnforceSiteScope(...)`, so a null resolve skipped the
check entirely and a site-scoped caller passed the gate for any id in the
system. Authorization now fails CLOSED: a target that cannot be PROVEN to sit
inside the caller's scope is treated as outside it.

The defect turned out to have THREE more instances than the register recorded.
Besides `EnforceSiteScopeForInstance` and `EnforceSiteScopeForIdentifier`, the
same inline shape sat in `HandleGetInstance`, `HandleGetSite` and
`HandleGetDataConnection` — read handlers that resolve their own target and so
never call the helpers. Those were the sharper half of the bug: they answered
success-with-null for a nonexistent id and Unauthorized for an out-of-scope
one, making the pair an id-enumeration oracle over the whole fleet. All five
now route through one shared `DenyUnresolvedTargetIfScoped` arm.

Two properties are load-bearing and pinned by tests:
  - System-wide callers (Administrator, or a Deployer with no site grants) are
    untouched — they return at the guards above the lookup and keep the
    handler's ordinary "not found" / null answer.
  - The denial is indistinguishable from an out-of-scope denial: same
    ManagementUnauthorized shape, and a message that never states whether the
    target exists.

Register row 99 — CLI `audit query --status delivered` failed client-side while
the server would have accepted it: `AcceptOnlyFromAmong` matches ordinally
against the capitalised literals. Same treatment row 88 gave `deploy status` —
the client-side gate is removed, the valid set moves into the option help text,
and the server becomes the single authoritative check.

That required ADDING the server check, not just relying on one: the shared
audit filter parser was LAX, silently dropping an unrecognised value and
leaving the dimension unconstrained — so removing the CLI gate alone would have
turned a loud client-side failure into a plausible, complete-looking page that
did not answer the question asked. New `ParseEnumListStrict` (case-insensitive,
rejects ordinals — `Enum.TryParse` accepts "3", and a filter is a name-based
contract) backs the ManagementService /api/audit/query + /api/audit/export
endpoints, which now return 400 BAD_REQUEST naming the valid set.

Other AcceptOnlyFromAmong sites surveyed in the audit group: `--channel`,
`--kind`, `--status` on BOTH `query` and `export` (6 uses) plus `export
--format` (rejected `--format CSV` though the server lowercases it) — all seven
fixed here. Deliberately left alone: `template folder reorder --direction`
(pure client-side literal, no server-side parse to defer to) and the global
`--format json|table` (CLI-local output selection, never sent to a server).

The CentralUI AuditLogPage drill-in parser and the CentralUI export endpoint it
feeds deliberately KEEP the lax parse — they read a query string a human may
have bookmarked, where a stale fragment must still render the page. Both
contracts now live side by side in AuditQueryParamParsers and are documented as
non-reconcilable.

Docs: Component-ManagementService.md gains a "Site-scope gate: fail-closed on
an unresolvable target" section and a strict-filter note on the audit
endpoints; Component-Security.md records the fail-closed shape under Deployer
site scoping; the CLI README marks the audit filter values case-insensitive and
states the no-silent-drop / no-ordinals contract.

Tests: 5 new ManagementActorTests fail before the row-98 fix (verified by
reverting ManagementActor.cs) and cover scoped+nonexistent -> denied,
system-wide+nonexistent -> unchanged (both Administrator and no-grant Deployer),
scoped+in-scope -> allowed, and the indistinguishability property. 21 CLI tests
fail before the row-99 fix. Four pre-existing tests that pinned the removed
client-side gate were rewritten to pin the new contract.
2026-08-17 06:05:29 -04:00

444 lines
20 KiB
C#

using System.CommandLine;
using ZB.MOM.WW.ScadaBridge.CLI.Commands;
using ZB.MOM.WW.ScadaBridge.Commons.Messages.Management;
namespace ZB.MOM.WW.ScadaBridge.CLI.Tests;
/// <summary>
/// Regression tests for CLI-013 — the command-tree wiring was untested. These tests
/// build every command group and assert the tree is well-formed (every leaf has an
/// action, no group is empty), and that every management command record the CLI sends
/// resolves via <see cref="ManagementCommandRegistry"/> (so command-name derivation
/// never throws at runtime).
/// </summary>
public class CommandTreeTests
{
private static readonly Option<string> Url = new("--url") { Recursive = true };
private static readonly Option<string> Username = new("--username") { Recursive = true };
private static readonly Option<string> Password = new("--password") { Recursive = true };
private static readonly Option<string> Format = CliOptions.CreateFormatOption();
// NOTE: this list MUST stay in sync with the rootCommand.Add(...) calls in
// src/ZB.MOM.WW.ScadaBridge.CLI/Program.cs. When a new command group is added (or one is
// removed/renamed), update this array and bump the count assertion in
// AllCommandGroups_Build_WithoutThrowing accordingly.
private static IEnumerable<Command> AllCommandGroups() => new[]
{
TemplateCommands.Build(Url, Format, Username, Password),
InstanceCommands.Build(Url, Format, Username, Password),
SiteCommands.Build(Url, Format, Username, Password),
DeployCommands.Build(Url, Format, Username, Password),
DataConnectionCommands.Build(Url, Format, Username, Password),
ExternalSystemCommands.Build(Url, Format, Username, Password),
NotificationCommands.Build(Url, Format, Username, Password),
SecurityCommands.Build(Url, Format, Username, Password),
AuditLogCommands.Build(Url, Format, Username, Password),
AuditCommands.Build(Url, Format, Username, Password),
HealthCommands.Build(Url, Format, Username, Password),
DebugCommands.Build(Url, Format, Username, Password),
SharedScriptCommands.Build(Url, Format, Username, Password),
DbConnectionCommands.Build(Url, Format, Username, Password),
ApiMethodCommands.Build(Url, Format, Username, Password),
BundleCommands.Build(Url, Format, Username, Password),
CachedCallCommands.Build(Url, Format, Username, Password),
};
private static IEnumerable<Command> LeafCommands(Command command)
{
if (command.Subcommands.Count == 0)
{
yield return command;
yield break;
}
foreach (var sub in command.Subcommands)
foreach (var leaf in LeafCommands(sub))
yield return leaf;
}
[Fact]
public void AllCommandGroups_Build_WithoutThrowing()
{
var groups = AllCommandGroups().ToList();
// CLI-022: bump this count whenever a new top-level command group is
// registered in Program.cs. Current registered groups (17):
// template, instance, site, deploy, data-connection, external-system,
// notification, security, audit-config, audit, health, debug,
// shared-script, db-connection, api-method, bundle, cached-call.
Assert.Equal(17, groups.Count);
Assert.All(groups, g => Assert.False(string.IsNullOrWhiteSpace(g.Name)));
}
[Fact]
public void AllCommandGroups_Contains_AuditAndBundle()
{
// CLI-022: explicit group-presence assertion so the harness does not
// silently drift back to excluding new groups. Use names because that
// is what users actually type at the prompt.
var groupNames = AllCommandGroups().Select(g => g.Name).ToHashSet();
Assert.Contains("audit", groupNames);
Assert.Contains("bundle", groupNames);
}
[Fact]
public void AuditCommandGroup_HasQueryExportAndVerifyChain()
{
// CLI-022: pin the audit sub-command surface so a rename / accidental
// removal of one of these is caught.
var audit = AuditCommands.Build(Url, Format, Username, Password);
var subNames = audit.Subcommands.Select(c => c.Name).ToHashSet();
Assert.Contains("query", subNames);
Assert.Contains("export", subNames);
Assert.Contains("verify-chain", subNames);
}
[Fact]
public void BundleCommandGroup_HasExportPreviewAndImport()
{
// CLI-022: pin the bundle sub-command surface.
var bundle = BundleCommands.Build(Url, Format, Username, Password);
var subNames = bundle.Subcommands.Select(c => c.Name).ToHashSet();
Assert.Contains("export", subNames);
Assert.Contains("preview", subNames);
Assert.Contains("import", subNames);
}
[Fact]
public void EveryLeafCommand_HasAnAction()
{
// A leaf command with no action is dead wiring — invoking it would do nothing.
var leaves = AllCommandGroups().SelectMany(LeafCommands).ToList();
Assert.NotEmpty(leaves);
Assert.All(leaves, leaf =>
Assert.True(leaf.Action != null, $"Leaf command '{leaf.Name}' has no action."));
}
[Fact]
public void TemplateCompositionDelete_IsKeyedByIdOnly()
{
// CLI-015: the in-repo README documented `template composition delete` with
// --template-id / --instance-name, but the implementation keys deletion by the
// composition's own integer ID via a single --id option. Pin the real surface.
var template = TemplateCommands.Build(Url, Format, Username, Password);
var composition = template.Subcommands.Single(c => c.Name == "composition");
var delete = composition.Subcommands.Single(c => c.Name == "delete");
var optionNames = delete.Options.Select(o => o.Name).ToList();
Assert.Contains("--id", optionNames);
Assert.DoesNotContain("--template-id", optionNames);
Assert.DoesNotContain("--instance-name", optionNames);
}
[Fact]
public void TemplateNativeAlarmSource_HasAddListRemove()
{
var template = TemplateCommands.Build(Url, Format, Username, Password);
var group = template.Subcommands.Single(c => c.Name == "native-alarm-source");
var subNames = group.Subcommands.Select(c => c.Name).ToHashSet();
Assert.Contains("add", subNames);
Assert.Contains("list", subNames);
Assert.Contains("remove", subNames);
}
[Fact]
public void Deploy_HasSiteVerb_WithRequiredSiteId()
{
// WP2.5: bulk site deploy. Named `deploy site` to sit alongside
// `deploy instance` / `deploy artifacts` — the group's convention is that
// the verb names the SCOPE of the deploy.
var deploy = DeployCommands.Build(Url, Format, Username, Password);
var site = deploy.Subcommands.Single(c => c.Name == "site");
// --site-id is REQUIRED here, unlike `deploy artifacts` where omitting it
// means fleet-wide. A bulk instance deploy must never be accidentally
// fleet-wide.
Assert.NotEmpty(site.Parse([]).Errors);
Assert.Empty(site.Parse(["--site-id", "3"]).Errors);
}
[Fact]
public void InstanceNativeAlarmSource_HasSetAndClear()
{
var instance = InstanceCommands.Build(Url, Format, Username, Password);
var group = instance.Subcommands.Single(c => c.Name == "native-alarm-source");
var subNames = group.Subcommands.Select(c => c.Name).ToHashSet();
Assert.Contains("set", subNames);
Assert.Contains("clear", subNames);
}
[Fact]
public void TemplateFolder_HasFullManagementCommandParity()
{
// CLI/management parity follow-up (docs/plans/2026-05-11-templates-folder-hierarchy.md):
// the folder management commands shipped without any CLI surface. Pin the
// 1:1 verb set so a verb cannot silently disappear again.
var template = TemplateCommands.Build(Url, Format, Username, Password);
var folder = template.Subcommands.Single(c => c.Name == "folder");
var subNames = folder.Subcommands.Select(c => c.Name).ToHashSet();
Assert.Contains("list", subNames);
Assert.Contains("create", subNames);
Assert.Contains("rename", subNames);
Assert.Contains("move", subNames);
Assert.Contains("reorder", subNames);
Assert.Contains("delete", subNames);
}
[Fact]
public void TemplateFolderCreate_ParentIdIsOptional_SoRootIsReachable()
{
// Omitting --parent-id must parse cleanly — that is how a folder is created
// at the tree root (null ParentFolderId on CreateTemplateFolderCommand).
var template = TemplateCommands.Build(Url, Format, Username, Password);
var folder = template.Subcommands.Single(c => c.Name == "folder");
var create = folder.Subcommands.Single(c => c.Name == "create");
var parentOption = create.Options.Single(o => o.Name == "--parent-id");
var rootParse = create.Parse(new[] { "--name", "Dev" });
Assert.Empty(rootParse.Errors);
Assert.Null(rootParse.GetValue((Option<int?>)parentOption));
var nestedParse = create.Parse(new[] { "--name", "Sub", "--parent-id", "7" });
Assert.Empty(nestedParse.Errors);
Assert.Equal(7, nestedParse.GetValue((Option<int?>)parentOption));
}
[Fact]
public void TemplateFolderMove_ParentIdIsOptional_SoRootIsReachable()
{
var template = TemplateCommands.Build(Url, Format, Username, Password);
var folder = template.Subcommands.Single(c => c.Name == "folder");
var move = folder.Subcommands.Single(c => c.Name == "move");
var parentOption = move.Options.Single(o => o.Name == "--parent-id");
var parse = move.Parse(new[] { "--id", "3" });
Assert.Empty(parse.Errors);
Assert.Null(parse.GetValue((Option<int?>)parentOption));
}
[Theory]
[InlineData("up")]
[InlineData("down")]
public void TemplateFolderReorder_AcceptsUpAndDown(string direction)
{
var template = TemplateCommands.Build(Url, Format, Username, Password);
var folder = template.Subcommands.Single(c => c.Name == "folder");
var reorder = folder.Subcommands.Single(c => c.Name == "reorder");
var parse = reorder.Parse(new[] { "--id", "3", "--direction", direction });
Assert.Empty(parse.Errors);
}
[Theory]
[InlineData("sideways")]
// AcceptOnlyFromAmong is case-SENSITIVE, so the literals are lowercase only.
// The audit --channel/--kind/--status options USED to share this contract; they
// dropped AcceptOnlyFromAmong in register row 99 precisely because the
// case-sensitivity rejected values the server accepts. --direction keeps it: it is
// a pure client-side literal that never reaches a server-side parse, so there is no
// authoritative check behind it to defer to.
[InlineData("Up")]
public void TemplateFolderReorder_RejectsAnythingElse(string direction)
{
var template = TemplateCommands.Build(Url, Format, Username, Password);
var folder = template.Subcommands.Single(c => c.Name == "folder");
var reorder = folder.Subcommands.Single(c => c.Name == "reorder");
var parse = reorder.Parse(new[] { "--id", "3", "--direction", direction });
Assert.NotEmpty(parse.Errors);
}
[Fact]
public void TemplateFolderReorder_RequiresDirection()
{
var template = TemplateCommands.Build(Url, Format, Username, Password);
var folder = template.Subcommands.Single(c => c.Name == "folder");
var reorder = folder.Subcommands.Single(c => c.Name == "reorder");
var parse = reorder.Parse(new[] { "--id", "3" });
Assert.NotEmpty(parse.Errors);
}
// ========================================================================
// Register row 99: the audit filter options must NOT be case-sensitively
// gated client-side.
//
// `audit query --status delivered` used to fail at the CLI parse layer while
// the server would have accepted it — AcceptOnlyFromAmong matches ordinally
// against the capitalised literals. The valid set now lives in the help text
// and the server's strict, case-insensitive check is authoritative (the same
// treatment row 88 gave `deploy status`). These tests fail before that change.
// ========================================================================
public static TheoryData<string, string, string> AuditFilterValues() => new()
{
// subcommand, option, value — lowercase, uppercase and mixed case of a real member.
{ "query", "--status", "delivered" },
{ "query", "--status", "DELIVERED" },
{ "query", "--channel", "apioutbound" },
{ "query", "--kind", "apicall" },
{ "export", "--status", "parked" },
{ "export", "--channel", "notification" },
{ "export", "--kind", "dbwrite" },
};
[Theory]
[MemberData(nameof(AuditFilterValues))]
public void AuditFilterOptions_AcceptValuesInAnyCase(string subcommand, string option, string value)
{
var audit = AuditCommands.Build(Url, Format, Username, Password);
var cmd = audit.Subcommands.Single(c => c.Name == subcommand);
// `export` has three required options; supply them so the only thing under
// test is the filter value's own acceptance.
var args = subcommand == "export"
? new[] { "--since", "1h", "--until", "now", "--format", "csv", "--output", "out.csv", option, value }
: new[] { option, value };
var parse = cmd.Parse(args);
Assert.Empty(parse.Errors);
}
[Theory]
[InlineData("csv")]
[InlineData("CSV")]
[InlineData("jsonl")]
public void AuditExport_FormatOption_AcceptsValuesInAnyCase(string format)
{
// The server lowercases --format before matching and returns a 400 naming
// csv/jsonl/parquet for anything else, so the client-side literal gate was
// pure friction (register row 99).
var audit = AuditCommands.Build(Url, Format, Username, Password);
var export = audit.Subcommands.Single(c => c.Name == "export");
var parse = export.Parse(new[]
{
"--since", "1h", "--until", "now", "--format", format, "--output", "out.csv",
});
Assert.Empty(parse.Errors);
}
[Fact]
public void AuditQuery_UnrecognisedFilterValue_IsNotRejectedClientSide()
{
// Deliberate: the CLI no longer second-guesses the filter vocabulary. A bad
// value must reach the server, which answers 400 naming the valid set —
// one authoritative check instead of two that can drift apart.
var audit = AuditCommands.Build(Url, Format, Username, Password);
var query = audit.Subcommands.Single(c => c.Name == "query");
var parse = query.Parse(new[] { "--status", "NotAStatus" });
Assert.Empty(parse.Errors);
}
[Fact]
public void SiteArea_HasMoveVerb()
{
// CLI/management parity follow-up (docs/plans/2026-05-11-deployment-topology-page-design.md):
// AreaService.MoveAreaAsync had no management command and no CLI verb.
var site = SiteCommands.Build(Url, Format, Username, Password);
var area = site.Subcommands.Single(c => c.Name == "area");
var subNames = area.Subcommands.Select(c => c.Name).ToHashSet();
Assert.Contains("move", subNames);
}
[Fact]
public void SiteAreaMove_ParentIdIsOptional_SoSiteRootIsReachable()
{
// Omitting --parent-id is how an area is moved to the site root
// (null NewParentAreaId on MoveAreaCommand).
var site = SiteCommands.Build(Url, Format, Username, Password);
var area = site.Subcommands.Single(c => c.Name == "area");
var move = area.Subcommands.Single(c => c.Name == "move");
var parentOption = move.Options.Single(o => o.Name == "--parent-id");
var rootParse = move.Parse(new[] { "--id", "3" });
Assert.Empty(rootParse.Errors);
Assert.Null(rootParse.GetValue((Option<int?>)parentOption));
var reparentParse = move.Parse(new[] { "--id", "3", "--parent-id", "2" });
Assert.Empty(reparentParse.Errors);
Assert.Equal(2, reparentParse.GetValue((Option<int?>)parentOption));
}
[Fact]
public void SiteAreaMove_RequiresId()
{
var site = SiteCommands.Build(Url, Format, Username, Password);
var area = site.Subcommands.Single(c => c.Name == "area");
var move = area.Subcommands.Single(c => c.Name == "move");
var parse = move.Parse(Array.Empty<string>());
Assert.NotEmpty(parse.Errors);
}
[Fact]
public void TemplateList_HasSkipAndTakePagingOptions()
{
// arch-review P2: `template list` gained additive --skip/--take offset paging.
var template = TemplateCommands.Build(Url, Format, Username, Password);
var list = template.Subcommands.Single(c => c.Name == "list");
var optionNames = list.Options.Select(o => o.Name).ToList();
Assert.Contains("--skip", optionNames);
Assert.Contains("--take", optionNames);
}
[Fact]
public void InstanceList_HasSkipAndTakePagingOptions()
{
// arch-review P2: `instance list` gained additive --skip/--take offset paging.
var instance = InstanceCommands.Build(Url, Format, Username, Password);
var list = instance.Subcommands.Single(c => c.Name == "list");
var optionNames = list.Options.Select(o => o.Name).ToList();
Assert.Contains("--skip", optionNames);
Assert.Contains("--take", optionNames);
}
[Fact]
public void InstanceList_ParsesTakeOptionValue()
{
// Parse-level check that --take binds to an int value on the list command.
var instance = InstanceCommands.Build(Url, Format, Username, Password);
var list = instance.Subcommands.Single(c => c.Name == "list");
var takeOption = list.Options.Single(o => o.Name == "--take");
var parse = list.Parse(new[] { "--skip", "10", "--take", "5" });
Assert.Empty(parse.Errors);
Assert.Equal(5, parse.GetValue((Option<int?>)takeOption));
}
[Theory]
[InlineData(typeof(GetInstanceCommand))]
[InlineData(typeof(ListSitesCommand))]
[InlineData(typeof(CreateTemplateCommand))]
[InlineData(typeof(SetConnectionBindingsCommand))]
[InlineData(typeof(SetInstanceOverridesCommand))]
[InlineData(typeof(DebugSnapshotCommand))]
[InlineData(typeof(MgmtDeployInstanceCommand))]
[InlineData(typeof(MgmtDeploySiteCommand))]
[InlineData(typeof(QueryAuditLogCommand))]
[InlineData(typeof(ExportBundleCommand))]
[InlineData(typeof(PreviewBundleCommand))]
[InlineData(typeof(ImportBundleCommand))]
[InlineData(typeof(AddTemplateNativeAlarmSourceCommand))]
[InlineData(typeof(SetInstanceNativeAlarmSourceOverrideCommand))]
[InlineData(typeof(MoveAreaCommand))]
[InlineData(typeof(ListTemplateFoldersCommand))]
[InlineData(typeof(CreateTemplateFolderCommand))]
[InlineData(typeof(RenameTemplateFolderCommand))]
[InlineData(typeof(MoveTemplateFolderCommand))]
[InlineData(typeof(ReorderTemplateFolderCommand))]
[InlineData(typeof(DeleteTemplateFolderCommand))]
public void CommandPayloadTypes_ResolveViaRegistry(Type commandType)
{
// GetCommandName throws ArgumentException for an unregistered type — the CLI
// calls it for every command it sends, so each must round-trip.
var name = ManagementCommandRegistry.GetCommandName(commandType);
Assert.False(string.IsNullOrWhiteSpace(name));
Assert.Equal(commandType, ManagementCommandRegistry.Resolve(name));
}
}